home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 24 / CU Amiga Magazine's Super CD-ROM 24 (1998)(EMAP Images)(GB)(Track 1 of 2)[!][issue 1998-07].iso / CUCD / Programming / SWI / source / man / builtin.doc (.txt) < prev    next >
Encoding:
LaTeX Document  |  1998-04-15  |  153.7 KB  |  3,084 lines

  1. \chapter{Built-In Predicates}
  2. \section{Notation of Predicate Descriptions}
  3. We have tried to keep the predicate descriptions clear and concise.
  4. First the predicate name is printed in bold face, followed by the
  5. arguments in italics.  Arguments are preceded by a `+', `-' or `?' sign.
  6. `+' indicates the argument is input to the predicate, `-' denotes output
  7. and `?' denotes `either input or output'.%
  8.     \footnote{These marks do \strong{notx} suggest instantiation (e.g.\
  9.     var(+Var)).} Constructs like `op/3' refer to the predicate `op' with
  10.     arity `3'.
  11. \section{Consulting Prolog Source files}    \label{sec:consulting}
  12. SWI-Prolog source files normally have a suffix `\fileext{pl}'.
  13. Specifying the suffix is optional. All predicates that handle source
  14. files first check whether a file with suffix `\fileext{pl}' exists. If
  15. not the plain file name is checked for existence. Library files are
  16. specified by embedding the file name using the functor
  17. \functor{library}{1}. Thus `\file{foo}' refers to `\file{foo.pl}' or
  18. `\file{foo}' in the current directory, `\file{library(foo)}' refers to
  19. `\file{foo.pl}' or `\file{foo}' in one of the library directories
  20. specified by the dynamic predicate library_directory/1. The user may
  21. specify other `aliases' than \file{library} using the predicate
  22. file_search_path/2. This is strongly encouraged for managing complex
  23. applications. See also absolute_file_name/[2,3].
  24. SWI-Prolog recognises grammar rules as defined in \cite{Clocksin:87}.
  25. The user may define additional compilation of the source file by
  26. defining the dynamic predicate term_expansion/2. Transformations by this
  27. predicate overrule the systems grammar rule transformations. It is not
  28. allowed to use assert/1, retract/1 or any other database predicate in
  29. term_expansion/2 other than for local computational purposes.%
  30. \footnote{ It does work for consult, but makes it impossible to compile
  31. programs into a stand alone executable (see \secref{compilation})}
  32. Directives may be placed anywhere in a source file, invoking any
  33. predicate.  They are executed when encountered.  If the directive fails,
  34. a warning is printed.  Directives are specified by :-/1 or ?-/1.  There
  35. is no difference between the two.
  36. SWI-Prolog does not have a separate reconsult/1 predicate. Reconsulting
  37. is implied automatically by the fact that a file is consulted which is
  38. already loaded.
  39. \begin{description}
  40. \predicate{load_files}{2}{+Files, +Options}
  41. The predicate load_files/2 is the parent of all the other loading
  42. predicates. It currently supports a subset of the options of Quintus
  43. load_files/2. \arg{Files} is either specifies a single, or a list of
  44. source-files. The specification for a source-file is handled
  45. absolute_file_name/2. See this predicate for the supported expansions.
  46. \arg{Options} is a list of options using the format
  47. \begin{quote}
  48. \arg{OptionName}(\arg{OptionValue})
  49. \end{quote}
  50. The following options are currently supported:
  51. \begin{description}
  52.     \termitem{if}{Condition}
  53. Load the file only if the specified condition is satisfied. The value
  54. \const{true} loads the file unconditionally, \const{changed} loads the
  55. file if it was not loaded before, or has been modified since it was
  56. loaded the last time, \const{not_loaded} loads the file if it was not
  57. loaded before.
  58.     \termitem{must_be_module}{Bool}
  59. If \const{true}, raise an error if the file is not a module file.  Used by
  60. use_module/[1,2].
  61.     \termitem{imports}{ListOrAll}
  62. If \const{all} and the file is a module file, import all public
  63. predicates. Otherwise import only the named predicates. Each predicate
  64. is refered to as <name>/<arity>. This option has no effect if the file
  65. is not a module file.
  66.     \termitem{silent}{Bool}
  67. If \const{true}, load the file without printing a message. The specified
  68. value is the default for all files loaded as a result of loading the
  69. specified files.
  70. \end{description}
  71. \predicate{consult}{1}{+File}
  72. Read \arg{File} as a Prolog source file. \arg{File} may be a list of
  73. files, in which case all members are consulted in turn. \arg{File} may
  74. start with the csh(1) special sequences \file{~}, \file{~<user>} and
  75. \file{$<var>}. \arg{File} may also be \file{library(Name)}, in which
  76. case the libraries are searched for a file with the specified name. See
  77. also library_directory/1 and file_search_path/2. consult/1 may be
  78. abbreviated by just typing a number of file names in a list. Examples:
  79. \begin{center}\begin{tabular}{ll}
  80. \exam{?- consult(load).}        & \% consult \file{load} or \file{load.pl} \\
  81. \exam{?- [library(quintus)]}.   & \% load Quintus compatibility library \\
  82. \end{tabular}\end{center}
  83. Equivalent to load_files(Files, []).
  84. \predicate{ensure_loaded}{1}{+File}
  85. If the file is not already loaded, this is equivalent to consult/1.
  86. Otherwise, if the file defines a module, import all public predicates.
  87. Finally, if the file is already loaded, is not a module file and the
  88. context module is not the global user module, ensure_loaded/1 will
  89. call consult/1.
  90. With the semantics, we hope to get as closely possible to the clear
  91. semantics without the presence of a module system.  Applications using
  92. modules should consider using use_module/[1,2].  
  93. Equivalent to load_files(Files, [if(changed)]).
  94. \predicate{require}{1}{+ListOfNameAndArity}
  95. Declare that this file/module requires the specified predicates to be
  96. defined ``with their commonly accepted definition''.  This predicate
  97. originates from the Prolog portability layer for XPCE.  It is intended
  98. to provide a portable mechanism for specifying that this module requires
  99. the specified predicates.
  100. The implementation normally first verifies whether the predicate is
  101. already defined.  If not, it will search the libraries and load the
  102. required library.
  103. SWI-Prolog, having autoloading, does {\bf not} load the library. Instead
  104. it creates a procedure header for the predicate if this does not exist.
  105. This will flag the predicate as `undefined'.  See also check/0 and
  106. autoload/0.
  107. \predicate{make}{0}{}
  108. Consult all source files that have been changed since they were
  109. consulted.  It checks \arg{all} loaded source files: files loaded into a
  110. compiled state using \exam{pl -c \ldots} and files loaded using consult
  111. or one of its derivatives. make/0 is normally invoked by the edit/[0,1]
  112. and ed/[0,1] predicates. make/0 can be combined with the compiler to
  113. speed up the development of large packages. In this case compile the
  114. package using
  115. \begin{code}
  116. sun% pl -g make -o my_program -c file ...
  117. \end{code}
  118. If `my_program' is started it will first reconsult all source files
  119. that have changed since the compilation.
  120. \predicate{library_directory}{1}{?Atom}
  121. Dynamic predicate used to specify library directories.  Default
  122. \file{./lib}, \file{~/lib/prolog} and the system's library
  123. (in this order) are defined.  The user may add library directories
  124. using assert/1, asserta/1 or remove system defaults using retract/1.
  125.     \predicate{file_search_path}{2}{+Alias, ?Path}
  126. Dynamic predicate used to specify `path-aliases'.  This feature is
  127. best described using an example.  Given the definition
  128. \begin{code}
  129. file_search_path(demo, '~/demo').
  130. \end{code}
  131. the file specification \file{demo(myfile)} will be expanded to
  132. \file{~/demo/myfile}.  The second argument of file_search_path/2 may
  133. be another alias.
  134. Below is the initial definition of the file search path.  This path
  135. implies \file{swi(<Path>)} refers to a file in the SWI-Prolog home
  136. directory.  The alias \file{foreign(<Path>)} is intended for storing
  137. shared libraries (\fileext{so} or \fileext{DLL} files).  See also
  138. load_foreign_library/[1,2].
  139. \begin{code}
  140. user:file_search_path(library, X) :-
  141.         library_directory(X).
  142. user:file_search_path(swi, Home) :-
  143.         feature(home, Home).
  144. user:file_search_path(foreign, swi(ArchLib)) :-
  145.         feature(arch, Arch),
  146.         concat('lib/', Arch, ArchLib).
  147. user:file_search_path(foreign, swi(lib)).
  148. \end{code}
  149. The file_search_path/2 expansion is used by all loading predicates as
  150. well as by absolute_file_name/2.
  151.     \predicate{expand_file_search_path}{2}{+Spec, -Path}
  152. Unifies \arg{Path} will all possible expansions of the file name
  153. specification \arg{Spec}.  See also absolute_file_name/3.
  154.     \predicate{source_file}{1}{?File}
  155. Succeeds if \arg{File} was loaded using consult/1 or ensure_loaded/1.
  156. \arg{File} refers to the full path name of the file (see
  157. expand_file_name/2). The predicate source_file/1 backtracks over all
  158. loaded source files.
  159. \predicate{source_file}{2}{?Pred, ?File}
  160. Is true if the predicate specified by \arg{Pred} was loaded from file
  161. \arg{File}, where \arg{File} is an absolute path name (see
  162. expand_file_name/2).  Can be used with any instantiation pattern, but the
  163. database only maintains the source file for each predicate.  Predicates
  164. declared \const{multifile} (see multifile/1) cannot be found this way.
  165. \predicate{prolog_load_context}{2}{?Key, ?Value}
  166. Determine loading context.  The following keys are defined:
  167. \begin{center}
  168. \begin{tabular}{|l|p{4in}|}
  169. \hline
  170. \bf Key         & \bf Description \\
  171. \hline
  172. \const{module}        & Module into which file is loaded \\
  173. \const{file}          & File loaded \\
  174. \const{stream}        & Stream identifier (see current_input/1) \\
  175. \const{directory}     & Directory in which \arg{File} lives. \\
  176. \const{term_position} & Position of last term read.  Term
  177.                        of the form \mbox{\tt '\$stream_position'(0,<Line>,0,0,0)} \\
  178. \hline
  179. \end{tabular}
  180. \end{center}
  181. Quintus compatibility predicate.  See also source_location/2.
  182. \predicate{source_location}{2}{-File, -Line}
  183. If the last term has been read from a physical file (i.e.\ not from the
  184. file \const{user} or a string), unify \arg{File} with an absolute path to
  185. the file and \arg{Line} with the line-number in the file. New code
  186. should use prolog_load_context/2.
  187. \predicate{term_expansion}{2}{+Term1, -Term2}
  188. Dynamic predicate, normally not defined.  When defined by the user all
  189. terms read during consulting that are given to this predicate.  If the
  190. predicate succeeds Prolog will assert \arg{Term2} in the database rather
  191. then the read term (\arg{Term1}).  \arg{Term2} may be a term of a the
  192. form `?- \arg{Goal}' or `:- \arg{Goal}'.  \arg{Goal} is then treated as
  193. a directive. If \arg{Term2} is a list all terms of the list are stored
  194. in the database or called (for directives).  If \arg{Term2} is of the
  195. form below, the system will assert \arg{Clause} and record the indicated
  196. source-location with it.
  197. \begin{quote}
  198. \mbox{\tt '\$source_location'(<File>, <Line>):<Clause>}
  199. \end{quote}
  200. When compiling a module (see \chapref{modules} and the directive module/2),
  201. expand_term/2 will first try term_expansion/2 in the module being
  202. compiled to allow for term-expansion rules that are local to a module.
  203. If there is no local definition, or the local definition fails to
  204. translate the term, expand_term/2 will try user:term_expansion/2. For
  205. compatibility with SICStus and Quintus Prolog, this feature should not
  206. be used. See also expand_term/2.
  207. \predicate{expand_term}{2}{+Term1, -Term2}
  208. This predicate is normally called by the compiler to perform preprocessing.
  209. First it calls term_expansion/2.  If this predicate fails it performs
  210. a grammar-rule translation.  If this fails it returns the first argument.
  211. \predicate{at_initialization}{1}{+Goal}
  212. Register \arg{Goal} to be ran when the system initialises.
  213. Initialisation takes place after reloading a .qlf (formerly .wic) file
  214. as well as after reloading a saved-state.  The hooks are run in the
  215. order they were registered.  A warning message is issued if \arg{Goal}
  216. fails, but execution continues.  See also at_halt/1
  217. \predicate{at_halt}{1}{+Goal}
  218. Register \arg{Goal} to be ran when the system halts. The hooks are run
  219. in the order they were registered.  Success or failure executing a hook
  220. is ignored.  These hooks may not call halt/[0,1].
  221. \predicate{initialization}{1}{+Goal}
  222. Call \arg{Goal} and register it using at_initialization/1.  Directives
  223. that do other things that creating clauses, records, flags or setting
  224. predicate attributes should normally be written using this tag to
  225. ensure the initialisation is executed when a saved system starts.
  226. See also qsave_program/[1,2].
  227. \predicate{compiling}{0}{}
  228. Succeeds if the system is compiling source files with the \cmdlineoption{-c}
  229. option into an intermediate code file.  Can be used to perform code
  230. optimisations in expand_term/2 under this condition.
  231. \predicate{preprocessor}{2}{-Old, +New}
  232. Read the input file via a Unix process that acts as preprocessor. A
  233. preprocessor is specified as an atom. The first occurrence of the string
  234. `\const{\%f}' is replaced by the name of the file to be loaded. The
  235. resulting atom is called as a Unix command and the standard output of
  236. this command is loaded. To use the Unix C preprocessor one should
  237. define:
  238. \begin{code}
  239. ?- preprocessor(Old, '/lib/cpp -C -P %f'), consult(...).
  240. Old = none
  241. \end{code}
  242. \end{description}
  243. \subsection{Quick Load Files}
  244. The features described in this section should be regarded {\bf alpha}.
  245. As of version 2.0.0, SWI-Prolog supports compilation of individual
  246. or multiple Prolog sourcefiles into `Quick Load Files'.  A `Quick
  247. Load Files' (\fileext{qlf} file) stores the contents of the file in
  248. a precompiled format very similar to compiled files created using
  249. the \cmdlineoption{-b} and \cmdlineoption{-c} flags (see \secref{compilation}).
  250. These files load considerably faster than sourcefiles and are normally
  251. more compact.  They are machine independent and may thus be loaded
  252. on any implementation of SWI-Prolog.  Note however that clauses are
  253. stored as virtual machine instructions.  Changes to the compiler will
  254. generally make old compiled files unusable.
  255. Quick Load Files are created using qcompile/1.  They may be loaded
  256. explicitly using qload/1 or implicitly using consult/1 or one
  257. of the other file-loading predicates described in
  258. \secref{consulting}.  If consult is given the explicit
  259. \fileext{pl} file, it will load the Prolog source.  When given the
  260. \fileext{qlf} file, it will call qload/1 to load the file.  When no
  261. extension is specified, it will load the \fileext{qlf} file when present
  262. and the fileext{pl} file otherwise.
  263. \begin{description}
  264. \predicate{qcompile}{1}{+File}
  265. Takes a single file specification like consult/1 (i.e. accepts
  266. constructs like \file{library(LibFile)} and creates a Quick Load
  267. File from \arg{File}.  The file-extension of this file is \fileext{qlf}.
  268. The base name of the Quick Load File is the same as the input file.
  269. If the file contains `\exam{:- consult(\arg{+File})}' or `\exam{:-
  270. [\arg{+File}]}' statements, the referred files are compiled into the
  271. same \fileext{qlf} file. Other directives will be stored in the
  272. \fileext{qlf} file and executed in the same fashion as when loading the
  273. \fileext{pl} file.
  274. For term_expansion/2, the same rules as described in
  275. \secref{compilation} apply.
  276. Source references (source_file/2) in the Quick Load File refer to
  277. the Prolog source file from which the compiled code originates. 
  278. \predicate{qload}{1}{+File}
  279. Loads the `Quick Load File'.  It has the same semantics as consult/1
  280. for a normal sourcefile.  Equivalent to \exam{consult(\arg{File})}
  281. iff \arg{File} refers to a `Quick Load File'.
  282. \end{description}
  283. \section{Listing Predicates and Editor Interface}    \label{sec:listing}
  284. SWI-Prolog offers an interface to the Unix \program{vi} editor and
  285. the GNU~Emacs invocations \program{emacs} and \program{emacsclient}. Which
  286. editor is used is determined by the Unix environment variable
  287. \env{EDITOR}, which should hold the full pathname of the editor. If this
  288. variable is not defined, \program{vi} is used.%
  289.     \footnote{When using XPCE, you may wish to load
  290.               \file{library('emacs/swi_prolog')} to use XPCE/Prolog's
  291.               built-in editor.}
  292. After the user quits the editor, make/0 is invoked to reload all
  293. modified source files using consult/1. If the editor can be quit such
  294. that an exit status non-equal to 0 is returned make/0 will not be
  295. invoked. \arg{top} can do this by typing control-C, \arg{vi} cannot do
  296. this.
  297. A predicate specification is either a term with the same functor and arity
  298. as the predicate wanted, a term of the form \arg{Functor}/\arg{Arity} or a
  299. single atom.  In the latter case the database is searched for a
  300. predicate of this name and arbitrary arity (see current_predicate/2).
  301. When more than one such predicate exists the system will prompt for
  302. confirmation on each of the matched predicates. Predicates specifications
  303. are given to the `Do What I Mean' system (see dwim_predicate/2) if the
  304. requested predicate does not exist.
  305. \begin{description}
  306.     \predicate{ed}{1}{+Pred}
  307. Invoke the user's preferred editor on the source file of \arg{Pred}, 
  308. providing a search specification which searches for the predicate at
  309. the start of a line.
  310.     \predicate{ed}{0}{}
  311. Invoke ed/1 on the predicate last edited using ed/1.  Asks the user to
  312. confirm before starting the editor.
  313.     \predicate{edit}{1}{+File}
  314. Invoke the user's preferred editor on \arg{File}.  \arg{File} is a file
  315. specification as for consult/1 (but not a list).  Note that the file
  316. should exist.
  317.     \predicate{edit}{0}{}
  318. Invoke edit/1 on the file last edited using edit/1.  Asks the user to
  319. confirm before starting the editor.
  320.     \predicate{listing}{1}{+Pred}
  321. List specified predicates (when an atom is given all predicates with
  322. this name will be listed).  The listing is produced on the basis of the
  323. internal representation, thus loosing user's layout and variable name
  324. information.  See also portray_clause/1.
  325. \predicate{listing}{0}{}
  326. List all predicates of the database using listing/1.
  327.     \predicate{portray_clause}{1}{+Clause}
  328. Pretty print a clause as good as we can.  A clause should be specified
  329. as a term `\exam{<Head> :- <Body>}' (put brackets around it to avoid operator
  330. precedence problems).  Facts are represented as `\exam{<Head> :- true}'.
  331.     \predicate{edit_source}{1}{+Spec}
  332. A hook that may be defined in the module \const{user} to specify how
  333. the predicates ed/1 and edit/1 call the editor.  If ed/1 is invoking
  334. this hook, \arg{Spec} is a term of the format
  335. \begin{quote}
  336. \exam{\arg{File}:\arg{LineNo}:\arg{Name}/\arg{Arity}}
  337. \end{quote}
  338. Where \arg{File} and \arg{LineNo} represents the location of the
  339. predicate remembered by Prolog, and \arg{Name} and \arg{Arity} specify
  340. the predicate.  If invoked by edit/1, \arg{Spec} is an atom denoting the
  341. name of the file to be edited.  This hook is defined by the library
  342. \pllib{swi_prolog} distributed with the XPCE package for using XPCE
  343. to edit Prolog files.
  344. \end{description}
  345. \section{Verify Type of a Term}
  346. \begin{description}
  347. \predicate{var}{1}{+Term}
  348. Succeeds if \arg{Term} currently is a free variable.
  349. \predicate{nonvar}{1}{+Term}
  350. Succeeds if \arg{Term} currently is not a free variable.
  351. \predicate{integer}{1}{+Term}
  352. Succeeds if \arg{Term} is bound to an integer.
  353. \predicate{float}{1}{+Term}
  354. Succeeds if \arg{Term} is bound to a floating point number.
  355. \predicate{number}{1}{+Term}
  356. Succeeds if \arg{Term} is bound to an integer or a floating point number.
  357. \predicate{atom}{1}{+Term}
  358. Succeeds if \arg{Term} is bound to an atom.
  359. \predicate{string}{1}{+Term}
  360. Succeeds if \arg{Term} is bound to a string.
  361. \predicate{atomic}{1}{+Term}
  362. Succeeds if \arg{Term} is bound to an atom, string, integer or floating
  363. point number.
  364. \predicate{compound}{1}{+Term}
  365. Succeeds if \arg{Term} is bound to a compound term.  See also functor/3
  366. and =../2.
  367. \predicate{ground}{1}{+Term}
  368. Succeeds if \arg{Term} holds no free variables.
  369. \end{description}
  370. \section{Comparison and Unification or Terms}    \label{sec:compare}
  371. \subsection{Standard Order of Terms}
  372. Comparison and unification of arbitrary terms. Terms are ordered in the
  373. so called ``standard order''. This order is defined as follows:
  374. \begin{enumerate}
  375.     \item $\arg{Variables} < \arg{Atoms} < \arg{Strings}%
  376.     \footnote{Strings might be considered atoms in future versions. See
  377.               also \secref{strings}}
  378.           < \arg{Numbers} < \arg{Terms}$
  379.     \item $\arg{Old~Variable} < \arg{New~Variable}$%
  380.         \footnote{In fact the variables are compared on their (dereferenced)
  381.                   addresses. Variables living on the global stack are always
  382.                   $<$ than variables on the local stack.  Programs
  383.                   should not rely on the order in which variables are sorted.}
  384.     \item \arg{Atoms} are compared alphabetically.
  385.     \item \arg{Strings} are compared alphabetically.
  386.     \item \arg{Numbers} are compared by value. Integers and floats are
  387.           treated identically.
  388.     \item \arg{Terms} are first checked on their functor
  389.           (alphabetically), then on their arity and finally recursively on
  390.           their arguments, leftmost argument first.     
  391. \end{enumerate}
  392. \begin{description}
  393. \infixop{==}{+Term1}{+Term2}
  394. Succeeds if \arg{Term1} is equivalent to \arg{Term2}. A variable is only
  395. identical to a sharing variable.
  396. \infixop{\==}{+Term1}{+Term2}
  397. Equivalent to \exam{\Snot Term1 == Term2}.
  398. \infixop{=}{+Term1}{+Term2}
  399. Unify \arg{Term1} with \arg{Term2}. Succeeds if the unification succeeds.
  400. \infixop{\=}{+Term1}{+Term2}
  401. Equivalent to \exam{\Snot Term1 = Term2}.
  402. \infixop{=@=}{+Term1}{+Term2}
  403. Succeeds if \arg{Term1} is `structurally equal' to \arg{Term2}.
  404. Structural equivalence is weaker than equivalence (\predref{==}{2}), but
  405. stronger than unification (\predref{=}{2}).  Two terms are structurally equal if
  406. their tree representation is identical and they have the same `pattern'
  407. of variables.  Examples:
  408. \begin{quote}
  409. \begin{tabular}{rclc}
  410. \tt a           & \tt =@= & \tt A       & false \\
  411. \tt A           & \tt =@= & \tt B       & true \\
  412. \tt x(A,A)      & \tt =@= & \tt x(B,C)  & false \\
  413. \tt x(A,A)      & \tt =@= & \tt x(B,B)  & true \\
  414. \tt x(A,B)      & \tt =@= & \tt x(C,D)  & true \\
  415. \end{tabular}
  416. \end{quote}
  417. \infixop{\=@=}{+Term1}{+Term2}
  418. Equivalent to \exam{`\Snot Term1 =@= Term2'}.
  419. \infixop{@<}{+Term1}{+Term2}
  420. Succeeds if \arg{Term1} is before \arg{Term2} in the standard order of terms.
  421. \infixop{@=<}{+Term1}{+Term2}
  422. Succeeds if both terms are equal (\predref{==}{2}) or \arg{Term1} is before \arg{Term2} in
  423. the standard order of terms.
  424. \infixop{@>}{+Term1}{+Term2}
  425. Succeeds if \arg{Term1} is after \arg{Term2} in the standard order of terms.
  426. \infixop{@>=}{+Term1}{+Term2}
  427. Succeeds if both terms are equal (\predref{==}{2}) or \arg{Term1} is after \arg{Term2} in
  428. the standard order of terms.
  429. \predicate{compare}{3}{?Order, +Term1, +Term2}
  430. Determine or test the \arg{Order} between two terms in the standard
  431. order of terms. \arg{Order} is one of \const{<}, \const{>} or \const{=},
  432. with the obvious meaning.
  433. \end{description}
  434. \section{Control Predicates}
  435. The predicates of this section implement control structures.  Normally
  436. these constructs are translated into virtual machine instructions by
  437. the compiler.  It is still necessary to implement these constructs
  438. as true predicates to support meta-calls, as demonstrated in the
  439. example below. The predicate finds all currently defined atoms of 1
  440. character long. Note that the cut has no effect when called via one
  441. of these predicates (see !/0).
  442. \begin{code}
  443. one_character_atoms(As) :-
  444.         findall(A, (current_atom(A), atom_length(A, 1)), As).
  445. \end{code}
  446. \begin{description}
  447. \predicate{fail}{0}{}
  448. Always fail.  The predicate fail/0 is translated into a single virtual
  449. machine instruction.
  450. \predicate{true}{0}{}
  451. Always succeed. The predicate true/0 is translated into a single virtual
  452. machine instruction.
  453. \predicate{repeat}{0}{}
  454. Always succeed, provide an infinite number of choice points.
  455. \predicate{!}{0}{}
  456. Cut. Discard choice points of parent frame and frames created after the
  457. parent frame. Note that the control structures \predref{;}{2},
  458. \predref{|}{2}, \predref{->}{2} and \predref{\+}{1} are
  459. normally handled by the compiler and do not create a frame, which
  460. implies the cut operates through these predicates. Some examples are
  461. given below. Note the difference between {t3}/1 and {t4}/1. Also note
  462. the effect of call/1 in {t5}/0. As the argument of call/1 is evaluated
  463. by predicates rather than the compiler the cut has no effect.
  464. \begin{center}\begin{tabular}{ll}
  465. \exam{t1 :- (a, !, fail ; b).}          & \% cuts {a}/0 and {t1}/0 \\
  466. \exam{t2 :- (a -> b, ! ; c).}           & \% cuts {b}/0 and {t2}/0 \\
  467. \exam{t3(G) :- a, G, fail.}             & \% if `G = !' cuts {a}/0 and {t1}/1 \\
  468. \exam{t4(G) :- a, call(G), fail.}       & \% if `G = !' cut has no effect \\
  469. \exam{t5 :- call((a, !, fail ; b)).}    & \% Cut has no effect \\
  470. \exam{t6 :- \Snot (a, !, fail ; b).}& \% cuts {a}/0 and {t6}/0 \\
  471. \end{tabular}\end{center}
  472. \infixop{,}{+Goal1}{+Goal2}
  473. Conjunction.  Succeeds if both `Goal1' and `Goal2' can be proved.  It is
  474. defined as (this definition does not lead to a loop as the second comma
  475. is handled by the compiler):
  476. \begin{code}
  477. Goal1, Goal2 :- Goal1, Goal2.
  478. \end{code}
  479. \infixop{;}{+Goal1}{+Goal2}
  480. The `or' predicate is defined as:
  481. \begin{code}
  482. Goal1 ; _Goal2 :- Goal1.
  483. _Goal1 ; Goal2 :- Goal2.
  484. \end{code}
  485. \infixop{|}{+Goal1}{+Goal2}
  486. Equivalent to \predref{;}{2}.  Retained for compatibility only.  New code
  487. should use \predref{;}{2}. Still nice though for grammar rules.
  488. \infixop{->}{+Condition}{+Action}
  489. If-then and If-Then-Else. The \predref{->}{2} construct commits to
  490. the choices made at its left-hand side, destroying choice-points created
  491. inside the clause (by \predref{;}{2}), or by goals called by
  492. this clause. Unlike \predref{!}{0}, the choicepoint of the predicate as
  493. a whole (due to multiple clauses) is \strong{not} destroyed. The
  494. combination \predref{;}{2} and \predref{->}{2} is
  495. defines as:
  496. \begin{code}
  497. If -> Then; _Else :- If, !, Then.
  498. If -> _Then; Else :- !, Else.
  499. If -> Then :- If, !, Then.
  500. \end{code}
  501. Note that the operator precedence relation between \const{;} and
  502. \const{->} ensure \exam{If -> Then ; Else} is actually a term of the
  503. form \exam{;(->(If, Then), Else)}.  The first two clauses belong to
  504. the definition of \predref{;}{2}), while only the last defines
  505. \predref{->}{2}.
  506. \infixop{*->}{+Condition}{+Action ; +Else}
  507. This construct implements the so-called `soft-cut'. The control is
  508. defined as follows: If \arg{Condition} succeeds at least once, the
  509. semantics is the same as (\arg{Condition}, \arg{Action}). If
  510. \arg{Condition} does not succeed, the semantics is that of
  511. (\arg{Condition}, \arg{Else}). In other words, If \arg{Condition}
  512. succeeds at least once, simply behave as the conjunction of
  513. \arg{Condition} and \arg{Action}, otherwise execute \arg{Else}.
  514. \prefixop{\+}{+Goal}
  515. Succeeds if `Goal' cannot be proven (mnemonic: \chr{+} refers to {\em
  516. provable} and the backslash (\chr{\}) is normally used to
  517. indicate negation).
  518. \end{description}
  519. \section{Meta-Call Predicates}        \label{sec:metacall}
  520. Meta call predicates are used to call terms constructed at run time.
  521. The basic meta-call mechanism offered by SWI-Prolog is to use
  522. variables as a subclause (which should of course be bound to a valid
  523. goal at runtime).  A meta-call is slower than a normal call as it
  524. involves actually searching the database at runtime for the predicate,
  525. while for normal calls this search is done at compile time.
  526. \begin{description}
  527. \predicate{call}{1}{+Goal}
  528. Invoke \arg{Goal} as a goal. Note that clauses may have variables as
  529. subclauses, which is identical to call/1, except when the argument is
  530. bound to the cut. See \predref{!}{0}.
  531. \predicate{call}{2}{+Goal, +ExtraArg1, \ldots}        % 2..
  532. Append \arg{ExtraArg1, ExtraArg2, \ldots} to the argument list of
  533. \arg{Goal} and call the result. For example, \exam{call(plus(1), 2, X)}
  534. will call plus/3, binding \arg{X} to 3.
  535. The call/[2..] construct is handled by the compiler, which implies that
  536. redefinition as a predicate has no effect.  The predicates call/[2-6]
  537. are defined as true predicates, so they can be handled by interpreted
  538. code.
  539. \predicate{apply}{2}{+Term, +List}
  540. Append the members of \arg{List} to the arguments of \arg{Term} and call
  541. the resulting term. For example: \exam{apply(plus(1), [2, X])} will
  542. call \exam{plus(1, 2, X)}. apply/2 is incorporated in the virtual
  543. machine of SWI-Prolog. This implies that the overhead can be compared to
  544. the overhead of call/1. New code should use call/[2..] if the length of
  545. \arg{List} is fixed, which is more widely supported and faster because
  546. there is no need to build and examine the argument list.
  547. \predicate{not}{1}{+Goal}
  548. Succeeds when \arg{Goal} cannot be proven.  Retained for compatibility
  549. only. New code should use \predref{\+}{1}.
  550. \predicate{once}{1}{+Goal}
  551. Defined as:
  552. \begin{code}
  553. once(Goal) :-
  554.         Goal, !.
  555. \end{code}
  556. once/1 can in many cases be replaced with \predref{->}{2}. The only
  557. difference is how the cut behaves (see !/0). The following two clauses
  558. are identical:
  559. \begin{code}
  560. 1) a :- once((b, c)), d.
  561. 2) a :- b, c -> d.
  562. \end{code}
  563. \predicate{ignore}{1}{+Goal}
  564. Calls \arg{Goal} as once/1, but succeeds, regardless of whether
  565. \arg{Goal} succeeded or not. Defined as:
  566. \begin{code}
  567. ignore(Goal) :-
  568.         Goal, !.
  569. ignore(_).
  570. \end{code}
  571. \predicate{call_with_depth_limit}{3}{+Goal, +Limit, -Result}
  572. If \arg{Goal} can be proven without recursion deeper than \arg{Limit}
  573. levels, call_with_depth_limit/3 succeeds, binding \arg{Result} to the
  574. deepest recursion level used during the proof.  Otherwise, \arg{Result}
  575. is unified with \const{depth_limit_exceeded} if the limit was exceeded
  576. during the proof, or the entire predicate fails if \arg{Goal} fails
  577. without exceeding \arg{Limit}.
  578. The depth-limit is guarded by the internal machinery. This differ from
  579. the depth computed based on a theoretical model. For example, true/0 is
  580. translated into an inlined virtual machine instruction. Also, repeat/0
  581. is not implemented as below, but as a non-deterministic foreign
  582. predicate.
  583. \begin{code}
  584. repeat.
  585. repeat :-
  586.     repeat.
  587. \end{code}
  588. As a result, call_with_depth_limit/3 may still loop inifitly on programs
  589. that should theoretically finish in finite time. This problem can be
  590. cured by using Prolog equivalents to such built-in predicates.
  591. This predicate may be used for theorem-provers to realise techniques
  592. like \jargon{iterrative deepening}.  It was implemented after discussion
  593. with Steve Moyle \email{smoyle@ermine.ox.ac.uk}.
  594. \end{description}
  595. \section{ISO compliant Exception handling}   \label{sec:exception}
  596. SWI-Prolog defines the predicates catch/3 and throw/1 for ISO compliant
  597. raising and catching of exceptions. In the current implementation
  598. (2.9.0), only part of the built-in predicates generate exceptions. In
  599. general, exceptions are implemented for I/O and arithmetic.
  600. \begin{description}
  601.     \predicate{catch}{3}{:Goal, +Catcher, :Recover}
  602. Behaves as call/1 if no exception is raised when executing \arg{Goal}.
  603. If a exception is raised using throw/1 while \arg{Goal} executes, and
  604. the \arg{Goal} is the innermost goal for which \arg{Catcher} unifies
  605. with the argument of throw/1, all choicepoints generated by \arg{Goal}
  606. are cut, and \arg{Recover} is called as in call/1.
  607. The overhead of calling a goal through catch/3 is very comparable to
  608. call/1.  Recovery from an exception has a similar overhead.
  609.     \predicate{throw}{1}{+Exception}
  610. Raise an exception. The system will look for the innermost catch/3
  611. ancestor for which \arg{Exception} unifies with the \arg{Catcher}
  612. argument of the catch/3 call.  See catch/3 for details.
  613. If there is no catch/3 willing to catch the error in the current Prolog
  614. context, the toplevel (prolog/0) catches the error and prints a warning
  615. message. If an exception was raised in a callback from C (see
  616. \chapref{foreign}), PL_next_solution() will fail and the exception
  617. context can be retrieved using PL_exception().
  618. \end{description}
  619. \subsection{Debugging and exceptions}
  620. \index{exceptions,debugging}%
  621. \index{debugging,exceptions}%
  622. Before the introduction of exceptions in SWI-Prolog a runtime error
  623. was handled by printing an error message, after which the predicate
  624. failed.  If the feature (see feature/2) \const{debug_on_error} was
  625. in effect (default), the tracer was switched on.  The combination of
  626. the error message and trace information is generally sufficient to
  627. locate the error.
  628. With exception handling, things are different. A programmer may wish to
  629. trap an exception using catch/3 to avoid it reaching the user. If the
  630. exception is not handled by user-code, the interactive toplevel will
  631. trap it to prevent termination.
  632. If we do not take special precautions, the context information
  633. associated with an unexpected exception (i.e.\ a programming error) is
  634. lost. Therefore, if an exception is raised, which is not caught using
  635. catch/3 and the toplevel is running, the error will be printed, and the
  636. system will enter trace mode.
  637. If the system is in an non-interactive callback from foreign code and
  638. there is no catch/3 active in the current context, it cannot determine
  639. whether or not the exception will be caught by the external routine
  640. calling Prolog.  It will then base its behaviour on the feature
  641. debug_on_error:
  642. \begin{itemlist}
  643.     \item [feature(debug_on_error, false)]
  644. The exception does not trap the debugger and is returned to the foreign
  645. routine calling Prolog, where it can be accessed using PL_exception().
  646. This is the default.
  647.     \item [feature(debug_on_error, true)]
  648. If the exception is not caught by Prolog in the current context, it will
  649. trap the tracer to help analysing the context of the error.
  650. \end{itemlist}
  651. While looking for the context in which an exception takes place, it is
  652. adviced to switch on debug mode using the predicate debug/0.
  653. \subsection{The exception term}        \label{sec:exceptterm}
  654. Builtin predicates generates exceptions using a term
  655. \term{error}{Formal, Context}.  The first argument is the `formal'
  656. description of the error, specifying the class and generic defined
  657. context information.  When applicable, the ISO error-term definition
  658. is used.  The second part describes some additional context to help
  659. the programmer while debugging.  In its most generic form this is
  660. a term of the form \term{context}{Name/Arity, Message}, where
  661. \arg{Name}/\arg{Arity} describes the built-in predicate that raised
  662. the error, and \arg{Message} provides an additional description of
  663. the error.  Any part of this structure may be a variable if no
  664. information was present.
  665. \subsection{Printing a message from an exception}
  666. The predicate print_message/2 may be used to print an exception term
  667. in a human readable format:
  668. \begin{description}
  669.     \predicate{print_message}{2}{+Kind, +Term}
  670. This predicate is modelled after the Quintus predicate with the same
  671. name, though its current implementation is incomplete.  It is used
  672. only for printing messages from exceptions from built-in predicates.
  673. \arg{Kind} is one of \const{informational}, \const{warning},
  674. const{error}, \const{help} or \const{silent}.  Currently only
  675. \const{error} is defined.  \arg{Term} is an \funcref{error}{2}
  676. term described in \secref{exceptterm}.  A human-readable message
  677. is printed to the stream \const{user_error}.
  678. This predicate first obtains the `human translation' of \arg{Term} and
  679. then calls message_hook/3.  If this fails the message is printed to
  680. the stream \const{user_error}.
  681. The print_message/2 predicate and its rules are in the file
  682. \file{<plhome>/boot/messages.pl}, which may be inspected for more
  683. information on the error messages and related error terms.
  684.     \predicate{message_hook}{3}{+Term, +Kind, +Message}
  685. Hook predicate that may be define in the module \const{user} to
  686. intercept messages from print_message/2. \arg{Term} and \arg{Kind} are
  687. the same as passed to print_message/2. \arg{Message} is a string
  688. containing the human readable translation of the message. If this
  689. predicate succeeds, print_message/2 considers the message printed.
  690. This predicate should be defined dynamic and multifile to allow other
  691. modules defining clauses for it too.
  692. \end{description}
  693. \section{Advanced control-structures: blocks}
  694. \index{exception-handling}
  695. The predicates of this section form a tightly related set for
  696. realising premature successful or failing exits from a \arg{block}.
  697. These predicates are first of all useful for error-recovery.  They
  698. were primarily implemented for compatibility reasons.
  699. \begin{description}
  700. \predicate{block}{3}{+Label, +Goal, -ExitValue}
  701. Execute \arg{Goal} in a \arg{block}.  \arg{Label} is the name of the
  702. block.  \arg{Label} is normally an atom, but the system imposes
  703. no type constraints and may even be a variable.  \arg{ExitValue}
  704. is normally unified to the second argument of an exit/2 call
  705. invoked by \arg{Goal}.
  706. \predicate{exit}{2}{+Label, +Value}
  707. Calling exit/2 makes the innermost \arg{block} which \arg{Label} unifies
  708. exit. The block's \arg{ExitValue} is unified with \arg{Value}. If this
  709. unification fails the block fails.
  710. \predicate{fail}{1}{+Label}
  711. Calling fail/1 makes the innermost \arg{block} which \arg{Label}
  712. unifies fail immediately.  Implemented as
  713. \begin{code}
  714. fail(Label) :- !(Label), fail.
  715. \end{code}
  716. \predicate{!}{1}{+Label}
  717. Cut all choice-points created since the entry of the innermost
  718. \arg{block} which \arg{Label} unifies.
  719. \end{description}
  720. The example below illustrate these constructs to immediately report a
  721. syntax-error from a `deep-down' procedure to the outside world without
  722. passing it as an argument `all-over-the-place'.
  723. \begin{code}
  724. parse(RuleSet, InputList, Rest) :-
  725.         block(syntaxerror, phrase(RuleSet, InputList, Rest), Error),
  726.         (   var(Error)
  727.         ->  true
  728.         ;   format('Syntax-error: ~w~n', Error),
  729.             fail
  730.         ).
  731. integer(N) -->
  732.         digit(D1), !, digits(Ds),
  733.         { name(N, [D1|Ds]) }.
  734. digits([D|R]) --> digit(D), digits(R).
  735. digits(_) --> letter(_), !, { exit(syntaxerror, 'Illegal number') }.
  736. digits([]) --> [].
  737. digit(D, [D|R], R)  :- between(0'0, 0'9, D).
  738. letter(D, [D|R], R) :- between(0'a, 0'z, D).
  739. \end{code}
  740. \section{Grammar rule interface (phrase)}
  741. The predicates below may be called to activate a grammar-rule set:
  742. \begin{description}
  743. \predicate{phrase}{2}{+RuleSet, +InputList}
  744. Equivalent to \exam{phrase(\arg{RuleSet}, \arg{InputList}, [])}.
  745. \predicate{phrase}{3}{+RuleSet, +InputList, -Rest}
  746. Activate the rule-set with given name.  `InputList' is the list of tokens
  747. to parse, `Rest' is unified with the remaining tokens if the sentence is
  748. parsed correctly.
  749. \end{description}
  750. \section{Database}
  751. SWI-Prolog offers three different database mechanisms. The first one is
  752. the common assert/retract mechanism for manipulating the clause
  753. database. As facts and clauses asserted using assert/1 or one of its
  754. derivatives become part of the program these predicates compile the term
  755. given to them. retract/1 and retractall/1 have to unify a term and
  756. therefore have to decompile the program. For these reasons the
  757. assert/retract mechanism is expensive. On the other hand, once compiled, 
  758. queries to the database are faster than querying the recorded database
  759. discussed below.  See also dynamic/1.
  760. The second way of storing arbitrary terms in the database is using the
  761. ``recorded database''. In this database terms are associated with a
  762. \arg{key}. A key can be an atom, integer or term. In the last case
  763. only the functor and arity determine the key. Each key has a chain of
  764. terms associated with it. New terms can be added either at the head or
  765. at the tail of this chain. This mechanism is considerably faster than
  766. the assert/retract mechanism as terms are not compiled, but just copied
  767. into the heap.
  768. The third mechanism is a special purpose one.  It associates an integer
  769. or atom with a key, which is an atom, integer or term.  Each key can
  770. only have one atom or integer associated with it.  It again is
  771. considerably faster than the mechanisms described above, but can only be
  772. used to store simple status information like counters, etc.
  773. \begin{description}
  774.     \predicate{abolish}{1}{:PredicateIndicator}
  775. Removes all clauses of a predicate with functor \arg{Functor} and arity
  776. \arg{Arity} from the database.  Unlike version 1.2, all predicate attributes
  777. (dynamic, multifile, index, etc.) are reset to their defaults.  Abolishing
  778. an imported predicate only removes the import link; the predicate
  779. will keep its old definition in its definition module.  For `cleanup' of
  780. the dynamic database, one should use retractall/1 rather than abolish/2.
  781.     \predicate{abolish}{2}{+Name, +Arity}
  782. Same as \exam{abolish(Name/Arity)}.  The predicate abolish/2 conforms to
  783. the Edinburgh standard, while abolish/1 is ISO compliant.
  784.     \predicate{redefine_system_predicate}{1}{+Head}
  785. This directive may be used both in module \const{user} and in normal
  786. modules to redefine any system predicate.  If the system definition is
  787. redefined in module \const{user}, the new definition is the default
  788. definition for all sub-modules.  Otherwise the redefinition is local
  789. to the module.  The system definition remains in the module \const{system}.
  790. Redefining system predicate facilitates the definition of compatibility
  791. packages.  Use in other context is discouraged.
  792. \predicate{retract}{1}{+Term}
  793. When \arg{Term} is an atom or a term it is unified with the first unifying fact
  794. or clause in the database. The fact or clause is removed from the database.
  795. \predicate{retractall}{1}{+Head}
  796. All facts or clauses in the database for which the \arg{head}
  797. unifies with \arg{Head} are removed.%
  798.     \footnote{Note that the definition has changed since version 2.0.6.
  799.               See release notes.}
  800. \predicate{assert}{1}{+Term}
  801. Assert a fact or clause in the database. \arg{Term} is asserted as the last
  802. fact or clause of the corresponding predicate.
  803. \predicate{asserta}{1}{+Term}
  804. Equivalent to assert/1, but \arg{Term} is asserted as first clause or fact
  805. of the predicate.
  806. \predicate{assertz}{1}{+Term}
  807. Equivalent to assert/1.
  808. \predicate{assert}{2}{+Term, -Reference}
  809. Equivalent to assert/1, but \arg{Reference} is unified with a unique
  810. reference to the asserted clause. This key can later be used with
  811. clause/3 or erase/1.
  812. \predicate{asserta}{2}{+Term, -Reference}
  813. Equivalent to assert/2, but \arg{Term} is asserted as first clause or fact
  814. of the predicate.
  815. \predicate{assertz}{2}{+Term, -Reference}
  816. Equivalent to assert/2.
  817. \predicate{recorda}{3}{+Key, +Term, -Reference}
  818. Assert \arg{Term} in the recorded database under key \arg{Key}. \arg{Key} is an
  819. integer, atom or term. \arg{Reference} is unified with a unique reference
  820. to the record (see erase/1).
  821. \predicate{recorda}{2}{+Key, +Term}
  822. Equivalent to \exam{recorda(\arg{Key}, \arg{Value}, _)}.
  823. \predicate{recordz}{3}{+Key, +Term, -Reference}
  824. Equivalent to recorda/3, but puts the \arg{Term} at the tail of the terms
  825. recorded under \arg{Key}.
  826. \predicate{recordz}{2}{+Key, +Term}
  827. Equivalent to \exam{recordz(\arg{Key}, \arg{Value}, _)}.
  828. \predicate{recorded}{3}{+Key, -Value, -Reference}
  829. Unify \arg{Value} with the first term recorded under \arg{Key} which does
  830. unify. \arg{Reference} is unified with the memory location of the record.
  831. \predicate{recorded}{2}{+Key, -Value}
  832. Equivalent to \exam{recorded(\arg{Key}, \arg{Value}, _)}.
  833. \predicate{erase}{1}{+Reference}
  834. Erase a record or clause from the database.  \arg{Reference} is an
  835. integer returned by recorda/3 or recorded/3, clause/3, assert/2,
  836. asserta/2 or assertz/2.  Other integers might conflict with the internal
  837. consistency of the system.  Erase can only be called once on a record or
  838. clause.  A second call also might conflict with the internal consistency
  839. of the system.%
  840. \bug{The system should have a special type for pointers, thus avoiding
  841. the Prolog user having to worry about consistency matters. Currently some
  842. simple heuristics are used to determine whether a reference is valid.}
  843. \predicate{flag}{3}{+Key, -Old, +New}
  844. \arg{Key} is an atom, integer or term. Unify \arg{Old} with the old
  845. value associated with \arg{Key}. If the key is used for the first time
  846. \arg{Old} is unified with the integer 0. Then store the value of
  847. \arg{New}, which should be an integer, float, atom or arithmetic
  848. expression, under \arg{Key}. flag/3 is a very fast mechanism for storing
  849. simple facts in the database. Example:
  850. \begin{code}
  851. :- module_transparent succeeds_n_times/2.
  852. succeeds_n_times(Goal, Times) :-
  853.         flag(succeeds_n_times, Old, 0),
  854.         Goal,
  855.         flag(succeeds_n_times, N, N+1),
  856.         fail ; flag(succeeds_n_times, Times, Old).
  857. \end{code}
  858. \end{description}
  859. \subsection{Indexing databases}
  860. By default, SWI-Prolog, as most other implementations, indexes
  861. predicates on their first argument.  SWI-Prolog allows indexing
  862. on other and multiple arguments using the declaration index/1.
  863. For advanced database indexing, it defines hash_term/2:
  864. \begin{description}
  865. \predicate{hash_term}{2}{+Term, -HashKey}
  866. If \arg{Term} is a ground term (see ground/1), \arg{HashKey} is
  867. unified with a positive integer value that may be used as a hash-key
  868. to the value.  If \arg{Term} is not ground, the predicate succeeds
  869. immediately, leaving \arg{HashKey} an unbound variable.
  870. This predicate may be used to build hash-tables as well as to exploit
  871. argument-indexing to find complex terms more quickly.
  872. The hash-key does not rely on temporary information like addresses of
  873. atoms and may be assumed constant over different invocations of
  874. SWI-Prolog.
  875. \end{description}
  876. \section{Declaring Properties of Predicates}    \label{ch:dynamic}
  877. \label{sec:declare}
  878. This section describes directives which manipulate attributes of
  879. predicate definitions.  The functors dynamic/1, multifile/1 and
  880. discontiguous/1 are operators of priority 1150 (see op/3), which
  881. implies the list of predicates they involve can just be a comma
  882. separated list: 
  883. \begin{code}
  884. :- dynamic
  885.         foo/0, 
  886.         baz/2.
  887. \end{code}
  888. On SWI-Prolog all these directives are just predicates. This implies
  889. they can also be called by a program.  Do not rely on this feature if
  890. you want to maintain portability to other Prolog implementations.
  891. \begin{description}
  892. \prefixop{dynamic}{+Functor/+Arity, \ldots}
  893. Informs the interpreter that the definition of the predicate(s) may change
  894. during execution (using assert/1 and/or retract/1).  Currently dynamic/1
  895. only stops the interpreter from complaining about undefined predicates (see
  896. unknown/2).  Future releases might prohibit assert/1 and retract/1 for
  897. not-dynamic declared procedures.
  898. \prefixop{multifile}{+Functor/+Arity, \ldots}
  899. Informs the system that the specified predicate(s) may be defined over
  900. more than one file. This stops consult/1 from redefining a predicate
  901. when a new definition is found.
  902. \prefixop{discontiguous}{+Functor/+Arity, \ldots}
  903. Informs the system that the clauses of the specified predicate(s) might
  904. not be together in the source file.  See also style_check/1.
  905. \predicate{index}{1}{+Head}
  906. Index the clauses of the predicate with the same name and arity as
  907. \arg{Head} on the specified arguments. \arg{Head} is a term of which all
  908. arguments are either `1' (denoting `index this argument') or `0'
  909. (denoting `do not index this argument'). Indexing has no implications
  910. for the semantics of a predicate, only on its performance. If indexing
  911. is enabled on a predicate a special purpose algorithm is used to select
  912. candidate clauses based on the actual arguments of the goal. This
  913. algorithm checks whether indexed arguments might unify in the clause
  914. head. Only atoms, integers and functors (e.g. name and arity of a term)
  915. are considered. Indexing is very useful for predicates with many clauses
  916. representing facts.
  917. Due to the representation technique used at most 4 arguments can be
  918. indexed. All indexed arguments should  be in the first 32 arguments of
  919. the predicate. If more than 4 arguments are specified for indexing only
  920. the first 4 will be accepted. Arguments above 32 are ignored for indexing.
  921. By default all predicates with $<arity> \geq 1$ are indexed on their
  922. first argument.  It is possible to redefine indexing on predicates that
  923. already have clauses attached to them.  This will initiate a scan
  924. through the predicates clause list to update the index summary
  925. information stored with each clause.
  926. If---for example---one wants to represents sub-types using a fact list
  927. \mbox{`sub_type(Sub, Super)'} that should be used both to determine sub- and
  928. super types one should declare {sub_type}/2 as follows:
  929. \begin{code}
  930. :- index(sub_type(1, 1)).
  931. sub_type(horse, animal).
  932. \end{code}
  933. \end{description}
  934. \section{Examining the Program}
  935. \begin{description}
  936. \predicate{current_atom}{1}{-Atom}
  937. Successively unifies \arg{Atom} with all atoms known to the system.
  938. Note that current_atom/1 always succeeds if \arg{Atom} is instantiated to
  939. an atom.
  940. \predicate{current_functor}{2}{?Name, ?Arity}
  941. Successively unifies \arg{Name} with the name and \arg{Arity} with the
  942. arity of functors known to the system.
  943. \predicate{current_flag}{1}{-FlagKey}
  944. Successively unifies \arg{FlagKey} with all keys used for flags (see
  945. flag/3).
  946. \predicate{current_key}{1}{-Key}
  947. Successively unifies \arg{Key} with all keys used for records (see
  948. recorda/3, etc.).
  949. \predicate{current_predicate}{2}{?Name, ?Head}
  950. Successively unifies \arg{Name} with the name of predicates currently
  951. defined and \arg{Head} with the most general term built from \arg{Name}
  952. and the arity of the predicate. This predicate succeeds for all
  953. predicates defined in the specified module, imported to it, or in one of
  954. the modules from which the predicate will be imported if it is called.
  955. \predicate{predicate_property}{2}{?Head, ?Property}
  956. Succeeds if \arg{Head} refers to a predicate that has property
  957. \arg{Property}. Can be used to test whether a predicate has a certain
  958. property, obtain all properties known for \arg{Head}, find all
  959. predicates having \arg{property} or even obtaining all information
  960. available about the current program. \arg{Property} is one of:
  961. \begin{description}
  962.     \termitem{interpreted}{}
  963. Is true if the predicate is defined in Prolog. We return true on this
  964. because, although the code is actually compiled, it is completely
  965. transparent, just like interpreted code.
  966.     \termitem{built_in}{}
  967. Is true if the predicate is locked as a built-in predicate. This
  968. implies it cannot be redefined in its definition module and it can
  969. normally not be seen in the tracer.
  970.     \termitem{foreign}{}
  971. Is true if the predicate is defined in the C language.
  972.     \termitem{dynamic}{}
  973. Is true if the predicate is declared dynamic using the dynamic/1
  974. declaration.
  975.     \termitem{multifile}{}
  976. Is true if the predicate is declared multifile using the multifile/1
  977. declaration.
  978.     \termitem{undefined}{}
  979. Is true if a procedure definition block for the predicate exists, 
  980. but there are no clauses in it and it is not declared dynamic. This is
  981. true if the predicate occurs in the body of a loaded predicate, an
  982. attempt to call it has been made via one of the meta-call predicates or
  983. the predicate had a definition in the past.  See the library package
  984. \arg{check} for example usage.
  985.     \termitem{transparent}{}
  986. Is true if the predicate is declared transparent using the
  987. module_transparent/1 declaration.
  988.     \termitem{exported}{}
  989. Is true if the predicate is in the public list of the context module.
  990.     \termitem{imported_from}{Module}
  991. Is true if the predicate is imported into the context module from
  992. module \arg{Module}.
  993.     \termitem{indexed}{Head}
  994. Predicate is indexed (see index/1) according to \arg{Head}. \arg{Head}
  995. is a term whose name and arity are identical to the predicate. The
  996. arguments are unified with `1' for indexed arguments, `0' otherwise.
  997.     \termitem{file}{FileName}
  998. Unify \arg{FileName} with the name of the sourcefile in which the
  999. predicate is defined.  See also source_file/2.
  1000.     \termitem{line_count}{LineNumber}
  1001. Unify \arg{LineNumber} with the line number of the first clause of the
  1002. predicate.  Fails if the predicate is not associated with a file.  See
  1003. also source_file/2.
  1004.     \termitem{number_of_clauses}{ClauseCount}
  1005. Unify \arg{ClauseCount} to the number of clauses associated with the
  1006. predicate.  Fails for foreign predicates.
  1007. \end{description}
  1008. \predicate{dwim_predicate}{2}{+Term, -Dwim}
  1009. `Do What I Mean' (`dwim') support predicate. \arg{Term} is a term, 
  1010. which name and arity are used as a predicate specification.  \arg{Dwim}
  1011. is instantiated with the most general term built from \arg{Name} and the
  1012. arity of a defined predicate that matches the predicate specified by
  1013. \arg{Term} in the `Do What I Mean' sense.  See dwim_match/2 for `Do
  1014. What I Mean' string matching.  Internal system predicates are
  1015. not generated, unless \exam{style_check(+dollar)} is active.  Backtracking
  1016. provides all alternative matches.
  1017. \predicate{clause}{2}{?Head, ?Body}
  1018. Succeeds when \arg{Head} can be unified with a clause head and \arg{Body} with the corresponding clause body.  Gives alternative clauses on
  1019. backtracking.  For facts \arg{Body} is unified with the atom \arg{true}.
  1020. Normally clause/2 is used to find clause definitions for a predicate, but it
  1021. can also be used to find clause heads for some body template.
  1022. \predicate{clause}{3}{?Head, ?Body, ?Reference}
  1023. Equivalent to clause/2, but unifies \arg{Reference} with a unique reference to
  1024. the clause (see also assert/2, erase/1). If \arg{Reference} is instantiated
  1025. to a reference the clause's head and body will be unified with \arg{
  1026. Head} and \arg{Body}.
  1027. \predicate{nth_clause}{3}{?Pred, ?Index, ?Reference}
  1028. Provides access to the clauses of a predicate using their index number.
  1029. Counting starts at 1.  If \arg{Reference} is specified it unifies \arg{Pred}
  1030. with the most general term with the same name/arity as the predicate and
  1031. \arg{Index} with the index-number of the clause.  Otherwise the name and
  1032. arity of \arg{Pred} are used to determine the predicate.  If \arg{Index}
  1033. is provided \arg{Reference} will be unified with the clause reference.
  1034. If \arg{Index} is unbound, backtracking will yield both the indices and
  1035. the references of all clauses of the predicate.  The following example
  1036. finds the 2nd clause of member/2:
  1037. \begin{code}
  1038. ?- nth_clause(member(_,_), 2, Ref), clause(Head, Body, Ref).
  1039. Ref = 160088
  1040. Head = system : member(G575, [G578|G579]) 
  1041. Body = member(G575, G579)
  1042. \end{code}
  1043. \predicate{clause_property}{2}{+ClauseRef, -Property}
  1044. Queries properties of a clause.  \arg{ClauseRef} is a reference to a
  1045. clause as produced by clause/3, nth_clause/3 or prolog_frame_attribute/3.
  1046. \arg{Property} is one of the following:
  1047. \begin{description}
  1048.     \termitem{file}{FileName}
  1049. Unify \arg{FileName} with the name of the sourcefile in which the
  1050. clause is defined.   Fails if the clause is not associated to a file.
  1051.     \termitem{line_count}{LineNumber}
  1052. Unify \arg{LineNumber} with the line number of the clause.  Fails if
  1053. the clause is not associated to a file.
  1054.     \termitem{fact}{}
  1055. True if the clause has no body.
  1056.     \termitem{erased}{}
  1057. True if the clause has been erased, but not yet reclaimed because
  1058. it is referenced.
  1059. \end{description}
  1060. \end{description}
  1061. \section{Input and Output}
  1062. SWI-Prolog provides two different packages for input and output.  One
  1063. confirms to the Edinburgh standard.  This package has a notion of
  1064. `current-input' and `current-output'.  The reading and writing
  1065. predicates implicitly refer to these streams.  In the second package,
  1066. streams are opened explicitly and the resulting handle is used as
  1067. an argument to the reading and writing predicate to specify the source
  1068. or destination.  Both packages are fully integrated; the user may
  1069. switch freely between them.
  1070. \subsection{Input and Output Using Implicit Source and Destination}
  1071. The package for implicit input and output destination is upwards
  1072. compatible to DEC-10 and C-Prolog.  The reading and writing predicates
  1073. refer to resp.  the current input- and output stream.  Initially these
  1074. streams are connected to the terminal.  The current output stream is
  1075. changed using tell/1 or append/1.  The current input stream is changed
  1076. using see/1.  The streams current value can be obtained using telling/1
  1077. for output- and seeing/1 for input streams.  The table below shows the
  1078. valid stream specifications.  The reserved names \const{user_input},
  1079. \const{user_output} and \const{user_error} are for neat integration with
  1080. the explicit streams.
  1081. \begin{center}
  1082. \begin{tabular}{|l|p{3in}|}
  1083. \hline
  1084. \const{user}         & This reserved name refers to the terminal \\
  1085. \const{user_input}   & Input from the terminal \\
  1086. \const{user_output}  & Output to the terminal \\
  1087. \const{user_error}   & Unix error stream (output only) \\
  1088. <Atom>               & Name of a Unix file \\
  1089. \const{pipe(<Atom>)} & Name of a Unix command \\
  1090. \hline
  1091. \end{tabular}
  1092. \end{center}
  1093. Source and destination are either a file, one of the reserved words
  1094. above, or a term `pipe(\arg{Command})'.  In the predicate descriptions
  1095. below we will call the source/destination argument `\arg{SrcDest}'.
  1096. Below are some examples of source/destination specifications.
  1097. \begin{center}\begin{tabular}{ll}
  1098. \exam{?- see(data).}       & \% Start reading from file `data'. \\
  1099. \exam{?- tell(stderr).}    & \% Start writing on the error stream. \\
  1100. \exam{?- tell(pipe(lpr)).} & \% Start writing to the printer.
  1101. \end{tabular}\end{center}
  1102. Another example of using the \functor{pipe}{1} construct is shown below.
  1103. Note that the \functor{pipe}{1} construct is not part of Prolog's
  1104. standard I/O repertoire.
  1105. \begin{code}
  1106. getwd(Wd) :-
  1107.         seeing(Old), see(pipe(pwd)), 
  1108.         collect_wd(String), 
  1109.         seen, see(Old), 
  1110.         atom_chars(Wd, String).
  1111. collect_wd([C|R]) :-
  1112.         get0(C), C \== -1, !, 
  1113.         collect_wd(R).
  1114. collect_wd([]).
  1115. \end{code}
  1116. \begin{description}
  1117. \predicate{see}{1}{+SrcDest}
  1118. Make \arg{SrcDest} the current input stream.  If \arg{SrcDest} was already opened for
  1119. reading with see/1 and has not been closed since, reading will be
  1120. resumed.  Otherwise \arg{SrcDest} will be opened and the file pointer is
  1121. positioned at the start of the file.
  1122. \predicate{tell}{1}{+SrcDest}
  1123. Make \arg{SrcDest} the current output stream.  If \arg{SrcDest} was already opened for
  1124. writing with tell/1 or append/1 and has not been closed since, writing
  1125. will be resumed.  Otherwise the file is created or---when
  1126. existing---truncated. See also append/1.
  1127. \predicate{append}{1}{+File}
  1128. Similar to tell/1, but positions the file pointer at the end of \arg{File}
  1129. rather than truncating an existing file. The pipe construct is not
  1130. accepted by this predicate.
  1131. \predicate{seeing}{1}{?SrcDest}
  1132. Unify the name of the current input stream with \arg{SrcDest}.
  1133. \predicate{telling}{1}{?SrcDest}
  1134. Unify the name of the current output stream with \arg{SrcDest}.
  1135. \predicate{seen}{0}{}
  1136. Close the current input stream. The new input stream becomes
  1137. \arg{user}.
  1138. \predicate{told}{0}{}
  1139. Close the current output stream. The new output stream becomes
  1140. \arg{user}.
  1141. \end{description}
  1142. \subsection{Explicit Input and Output Streams}
  1143. The predicates below are part of the Quintus compatible stream-based
  1144. I/O package.  In this package streams are explicitly created using the
  1145. predicate open/3.  The resulting stream identifier is then passed as a
  1146. parameter to the reading and writing predicates to specify the source
  1147. or destination of the data.
  1148. \begin{description}
  1149.     \predicate{open}{4}{+SrcDest, +Mode, -Stream, +Options}
  1150. ISO compliant predicate to open a stream. \arg{SrcDes} is either an
  1151. atom, specifying a Unix file, or a term `\exam{pipe(\arg{Command})}',
  1152. just like see/1 and tell/1. \arg{Mode} is one of \const{read},
  1153. \const{write}, \const{append} or \const{update}. Mode \const{append}
  1154. opens the file for writing, positioning the file-pointer at the end.
  1155. Mode \const{update} opens the file for writing, positioning the
  1156. file-pointer at the beginning of the file without truncating the file.
  1157. See also stream_position/3. \arg{Stream} is either a variable, in which
  1158. case it is bound to an integer identifying the stream, or an atom, in
  1159. which case this atom will be the stream identifier. The \arg{Options}
  1160. list can contain the following options:
  1161. \begin{description}
  1162.     \termitem{type}{Type}
  1163. Using type \const{text} (default), Prolog will write a text-file in
  1164. an operating-system compatible way. Using type \const{binary} the
  1165. bytes will be read or written without any translation. Note there is no
  1166. difference between the two on Unix systems.
  1167.     \termitem{alias}{Atom}
  1168. Gives the stream a name. The following two calls are identical, but only
  1169. the latter is allowed in ISO Prolog.
  1170. \begin{code}
  1171. ?- open(foo, read, in, []).
  1172. ?- open(foo, read, S, [alias(in)]).
  1173. \end{code}
  1174.     \termitem{eof_action}{Action}
  1175. Defines what happens if the end of the input stream is reached. Action
  1176. \const{eof_code} makes get0/1 and friends return -1 and read/1 and friends
  1177. return the atom \const{end_of_file}. Repetitive reading keeps yielding the
  1178. same result. Action \const{error} is like \const{eof_code}, but repetitive
  1179. reading will raise an error. With action \const{reset}, Prolog will
  1180. examine the file again and return more data if the file has grown.
  1181.     \termitem{buffer}{Buffering}
  1182. Defines output buffering. The atom \const{fullf} (default) defines full
  1183. buffering, \const{line} buffering by line, and \const{false} implies the
  1184. stream is fully unbuffered.  Smaller buffering is useful if another
  1185. process or the user is waiting for the output as it is being produced.
  1186. See also flush/0 and flush_output/1.  This option is not an ISO option.
  1187.     \termitem{close_on_abort}{Bool}
  1188. If \const{true} (default), the stream is closed on an abort (see
  1189. abort/0). If \const{false}, the stream is not closed. If it is an output
  1190. stream, it will be flushed however.  Useful for logfiles and if the
  1191. stream is associated to a process (using the \functor{pipe}{1}
  1192. construct).
  1193. \end{description}
  1194. The option \const{reposition} is not supported in SWI-Prolog.  All streams
  1195. connected to a file may be repositioned.
  1196. \predicate{open}{3}{+SrcDest, +Mode, ?Stream}
  1197. Equivalent to open/4 with an empty option-list.
  1198. \predicate{open_null_stream}{1}{?Stream}
  1199. Open a stream that produces no output.  All counting functions are
  1200. enabled on such a stream.  An attempt to read from a null-stream will
  1201. immediately signal end-of-file.  Similar to Unix \file{/dev/null}.
  1202. \arg{Stream} can be an atom, giving the null-stream an alias name.
  1203. \predicate{close}{1}{+Stream}
  1204. Close the specified stream.  If \arg{Stream} is not open an error
  1205. message is displayed.  If the closed stream is the current input or
  1206. output stream the terminal is made the current input or output.
  1207. \predicate{current_stream}{3}{?File, ?Mode, ?Stream}
  1208. Is true if a stream with file specification \arg{File}, mode \arg{Mode}
  1209. and stream identifier \arg{Stream} is open. The reserved streams
  1210. \const{user} and \const{user_error} are not generated by this predicate.
  1211. If a stream has been opened with mode \const{append} this predicate will
  1212. generate mode \const{write}.
  1213. \predicate{stream_position}{3}{+Stream, -Old, +New}
  1214. Unify the position parameters of \arg{Stream} with \arg{Old} and set them to
  1215. \arg{New}.  A position is represented by the following term:
  1216. \begin{code}
  1217. '$stream_position'(CharNo, LineNo, LinePos).
  1218. \end{code}
  1219. It is only possible to change the position parameters if the stream is
  1220. connected to a disk file. If the position is changed, the \arg{CharNo}
  1221. field determines the new position in the file.  The \arg{LineNo} and
  1222. \arg{LinePos} are copied in the stream administration.
  1223. \end{description}
  1224. \subsection{Switching Between Implicit and Explicit I/O}
  1225. The predicates below can be used for switching between the implicit-
  1226. and the explicit stream based I/O predicates.
  1227. \begin{description}
  1228. \predicate{set_input}{1}{+Stream}
  1229. Set the current input stream to become \arg{Stream}.  Thus, open(file,
  1230. read, Stream), set_input(Stream) is equivalent to see(file).
  1231. \predicate{set_output}{1}{+Stream}
  1232. Set the current output stream to become \arg{Stream}.
  1233. \predicate{current_input}{1}{-Stream}
  1234. Get the current input stream.  Useful to get access to the status
  1235. predicates associated with streams.
  1236. \predicate{current_output}{1}{-Stream}
  1237. Get the current output stream.
  1238. \predicate{dup_stream}{2}{+From, +To}
  1239. Duplicate the underlying data from stream \arg{From} to stream{To}, so
  1240. actions performed on either stream have the same effect.  The primary
  1241. goal of this predicate is to facilitate redirection of the user
  1242. interaction to allow for `interactor' windows.  For example, the
  1243. following code will redirect output to \const{user_output} and
  1244. \const{user_error} to an XPCE text window:
  1245. \begin{code}
  1246.     ...,
  1247.     pce_open(Window, append, Fd),
  1248.     dup_stream(user_output, Fd),
  1249.     dup_stream(user_error, Fd),
  1250. \end{code}
  1251. The old status of a stream can be stored by duplicating to a null-stream
  1252. as obtained using open_null_stream/1.
  1253. This predicate is SWI-Prolog specific.
  1254. \end{description}
  1255. \section{Status of Input and Output Streams}
  1256. \begin{description}
  1257. \predicate{wait_for_input}{3}{+ListOfStreams, -ReadyList, +TimeOut}
  1258. Wait for input on one of the streams in \arg{ListOfStreams} and return
  1259. a list of streams on which input is available in \arg{ReadyList}.
  1260. wait_for_input/3 waits for at most \arg{TimeOut} seconds.  \arg{Timeout} may be specified as a floating point number to specify
  1261. fractions of a second. If \arg{Timeout} equals 0, wait_for_input/3
  1262. waits indefinitely.  This predicate can be used to implement
  1263. timeout while reading and to handle input from multiple sources. The
  1264. following example will wait for input from the user and an
  1265. explicitly opened second terminal.  On return, \arg{Inputs} may hold
  1266. \const{user} or \arg{P4} or both.
  1267. \begin{code}
  1268. ?- open('/dev/ttyp4', read, P4),
  1269.    wait_for_input([user, P4], Inputs, 0).
  1270. \end{code}
  1271. \predicate{character_count}{2}{+Stream, -Count}
  1272. Unify \arg{Count} with the current character index.  For input streams
  1273. this is the number of characters read since the open, for output
  1274. streams this is the number of characters written. Counting starts at 0.
  1275. \predicate{line_count}{2}{+Stream, -Count}
  1276. Unify \arg{Count} with the number of lines read or written.  Counting
  1277. starts at 1.
  1278. \predicate{line_position}{2}{+Stream, -Count}
  1279. Unify \arg{Count} with the position on the current line. Note that this
  1280. assumes the position is 0 after the open.  Tabs are assumed to be
  1281. defined on each 8-th character and backspaces are assumed to reduce the
  1282. count by one, provided it is positive.
  1283. \predicate{fileerrors}{2}{-Old, +New}
  1284. Define error behaviour on errors when opening a file for reading or
  1285. writing. Valid values are the atoms \const{on} (default) and \const{off}.
  1286. First \arg{Old} is unified with the current value. Then the new value is
  1287. set to \arg{New}.%
  1288.     \footnote{Note that Edinburgh Prolog defines fileerrors/0 and
  1289.               nofileerrors/0.  As this does not allow you to switch back
  1290.               to the old mode I think this definition is better.}
  1291. \end{description}
  1292. \section{Primitive Character Input and Output}
  1293. \begin{description}
  1294. \predicate{nl}{0}{}
  1295. Write a newline character to the current output stream.  On Unix systems
  1296. nl/0 is equivalent to \exam{put(10)}.
  1297. \predicate{nl}{1}{+Stream}
  1298. Write a newline to \arg{Stream}.
  1299. \predicate{put}{1}{+Char}
  1300. Write \arg{Char} to the current output stream, \arg{Char} is either an
  1301. integer-expression evaluating to an ASCII value
  1302. ($0 \leq \arg{Char} \leq 255$) or an atom of one character.
  1303. \predicate{put}{2}{+Stream, +Char}
  1304. Write \arg{Char} to \arg{Stream}.
  1305. \predicate{tab}{1}{+Amount}
  1306. Writes \arg{Amount} spaces on the current output stream.  \arg{Amount}
  1307. should be an expression that evaluates to a positive integer (see
  1308. \secref{arith}).
  1309. \predicate{tab}{2}{+Stream, +Amount}
  1310. Writes \arg{Amount} spaces to \arg{Stream}.
  1311. \predicate{flush}{0}{}
  1312. Flush pending output on current output stream.  flush/0 is automatically
  1313. generated by read/1 and derivatives if the current input stream is \const{user} and the cursor is not at the left margin.
  1314. \predicate{flush_output}{1}{+Stream}
  1315. Flush output on the specified stream.  The stream must be open for
  1316. writing.
  1317. \predicate{ttyflush}{0}{}
  1318. Flush pending output on stream \arg{user}. See also flush/0.
  1319. \predicate{get0}{1}{-Char}
  1320. Read the current input stream and unify the next character with \arg{Char}.
  1321. \arg{Char} is unified with -1 on end of file.
  1322. \predicate{get0}{2}{+Stream, -Char}
  1323. Read the next character from \arg{Stream}.
  1324. \predicate{get}{1}{-Char}
  1325. Read the current input stream and unify the next non-blank character
  1326. with \arg{Char}. \arg{Char} is unified with -1 on end of file.
  1327. \predicate{get}{2}{+Stream, -Char}
  1328. Read the next non-blank character from \arg{Stream}.
  1329. \predicate{peek_byte}{1}{-Char}
  1330. Reads the next input character like get0/1, but does not remove it from
  1331. the input stream.  This predicate is ISO compliant.
  1332. \predicate{peek_byte}{2}{+Stream, -Char}
  1333. Reads the next input character like get0/2, but does not remove it from
  1334. the stream.  This predicate is ISO compliant.
  1335. \predicate{skip}{1}{+Char}
  1336. Read the input until \arg{Char} or the end of the file is encountered.
  1337. A subsequent call to get0/1 will read the first character after \arg{Char}.
  1338. \predicate{skip}{2}{+Stream, +Char}
  1339. Skip input (as skip/1) on \arg{Stream}.
  1340. \predicate{get_single_char}{1}{-Char}
  1341. Get a single character from input stream `user' (regardless of the
  1342. current input stream). Unlike get0/1 this predicate does not wait for a
  1343. return. The character is not echoed to the user's terminal. This
  1344. predicate is meant for keyboard menu selection etc.. If SWI-Prolog was
  1345. started with the \cmdlineoption{-tty} option this predicate reads an entire
  1346. line of input and returns the first non-blank character on this line, or
  1347. the ASCII code of the newline (10) if the entire line consisted of blank
  1348. characters.
  1349. \predicate{at_end_of_stream}{0}{}
  1350. Succeeds after the last character of the current input stream has
  1351. been read.  Also succeeds if there is no valid current input stream.
  1352. \predicate{at_end_of_stream}{1}{+Stream}
  1353. Succeeds after the last character of the named stream is read, or
  1354. \arg{Stream} is not a valid input stream.
  1355. \end{description}
  1356. \section{Term Reading and Writing}
  1357. This section describes the basic term reading and writing predicates.
  1358. The predicates term_to_atom/2 and atom_to_term/3 provide means for
  1359. translating atoms and strings to terms.  The predicates format/[1,2]
  1360. and writef/2 provide formatted output.
  1361. There are two ways to manipulate the output format.  The predicate
  1362. print/[1,2] may be programmed using portray/1.  The format of floating
  1363. point numbers may be manipulated using the feature (see feature/2)
  1364. \const{float_format}.
  1365. Reading is sensitive to the feature \const{character_escapes}, which
  1366. controls the interpretation of the \chr{\} character in quoted
  1367. atoms and strings.
  1368. \begin{description}
  1369.     \predicate{write_term}{2}{+Term, +Options}
  1370. The predicate write_term/2 is the generic form of all Prolog term-write
  1371. predicates.  Valid options are:
  1372. \begin{description}
  1373.     \termitem{quoted}{\const{true} or \const{false}}
  1374. If \const{true}, atoms and functors that needs quotes will be quoted.
  1375. The default is \const{false}.
  1376.     \termitem{ignore_ops}{\const{true} or \const{false}}
  1377. If \const{true}, the generic term-representation (<functor>(<args>
  1378. \ldots)) will be used for all terms,  Otherwise (default), operators,
  1379. list-notation and \verb${}$/1 will be written using their special
  1380. syntax.
  1381.     \termitem{numbervars}{\const{true} or \const{false}}
  1382. If \const{true}, terms of the format \verb|$VAR(N)|, where <N> is a
  1383. positive integer, will be written as a variable name. The default is
  1384. \const{false}.
  1385.     \termitem{portray}{\const{true} or \const{false}}
  1386. If \const{true}, the hook portray/1 is called before printing a term
  1387. that is not a variable.  If portray/1 succeeds, the term is considered
  1388. printed.  See also print/1.  The default is \const{false}.  This option
  1389. is an extension to the ISO write_term options.
  1390. \end{description}
  1391.     \predicate{write_term}{3}{+Stream, +Term, +Options}
  1392. As write_term/2, but output is sent to \arg{Stream} rather than the
  1393. current output.
  1394.     \predicate{write_canonical}{1}{+Term}
  1395. Write \arg{Term} on the current output stream using standard
  1396. parenthesised prefix notation (i.e. ignoring operator declarations).
  1397. Atoms that need quotes are quoted.  Terms written with this predicate
  1398. can always be read back, regardless of current operator declarations.
  1399. Equivalent to write_term/2 using the options \const{ignore_ops} and
  1400. \const{quoted}.
  1401.     \predicate{write_canonical}{2}{+Stream, +Term}
  1402. Write \arg{Term} in canonical form on \arg{Stream}.
  1403. \predicate{write}{1}{+Term}
  1404. Write \arg{Term} to the current output, using brackets and operators where
  1405. appropriate.   See feature/2 for controlling floating point output format.
  1406. \predicate{write}{2}{+Stream, +Term}
  1407. Write \arg{Term} to \arg{Stream}.
  1408. \predicate{writeq}{1}{+Term}
  1409. Write \arg{Term} to the current output, using brackets and operators where
  1410. appropriate. Atoms that need quotes are quoted. Terms written with this
  1411. predicate can be read back with read/1 provided the currently active
  1412. operator declarations are identical.
  1413. \predicate{writeq}{2}{+Stream, +Term}
  1414. Write \arg{Term} to \arg{Stream}, inserting quotes.
  1415. \predicate{print}{1}{+Term}
  1416. Prints \arg{Term} on the current output stream similar to write/1, 
  1417. but for each (sub)term of \arg{Term} first the dynamic predicate
  1418. portray/1 is called.  If this predicate succeeds \arg{print} assumes the
  1419. (sub)term has been written.  This allows for user defined term writing.
  1420. \predicate{print}{2}{+Stream, +Term}
  1421. Print \arg{Term} to \arg{Stream}.
  1422. \predicate{portray}{1}{+Term}
  1423. A dynamic predicate, which can be defined by the user to change the
  1424. behaviour of print/1 on (sub)terms.  For each subterm encountered that
  1425. is not a variable print/1 first calls portray/1 using the term as
  1426. argument.  For lists only the list as a whole is given to portray/1.  If
  1427. portray succeeds print/1 assumes the term has been written.
  1428. \predicate{read}{1}{-Term}
  1429. Read the next Prolog term from the current input stream and unify it
  1430. with \arg{Term}.  On a syntax error read/1 displays an error message, 
  1431. attempts to skip the erroneous term and fails.  On reaching end-of-file
  1432. \arg{Term} is unified with the atom \const{end_of_file}.
  1433. \predicate{read}{2}{+Stream, -Term}
  1434. Read \arg{Term} from \arg{Stream}.
  1435. \predicate{read_clause}{1}{-Term}
  1436. Equivalent to read/1, but warns the user for variables only occurring
  1437. once in a term (singleton variables) which do not start with an
  1438. underscore if \exam{style_check(singleton)} is active (default).
  1439. Used to read Prolog source files (see consult/1).  New code should
  1440. use read_term/2 with the option \exam{singletons(warning)}.
  1441. \predicate{read_clause}{2}{+Stream, -Term}
  1442. Read a clause from \arg{Stream}.  See read_clause/1.
  1443. \predicate{read_variables}{2}{-Term, -Bindings}
  1444. Similar to read/1, but \arg{Bindings} is unified with a list of
  1445. `$\arg{Name} = \arg{Var}$' tuples, thus providing access to the actual
  1446. variable names.  New code should use read_term/2 using the option
  1447. \exam{variables(X)}.
  1448. \predicate{read_variables}{3}{+Stream, -Term, -Bindings}
  1449. Read, returning term and bindings from \arg{Stream}. See
  1450. read_variables/2.
  1451. \predicate{read_term}{2}{-Term, +Options}
  1452. Read a term from the current input stream and unify the term with \arg{Term}. The reading is controlled by options from the list of \arg{Options}.   If this list is empty, the behaviour is the same as for
  1453. read/1.  The options are upward compatible to Quintus Prolog.  The
  1454. argument order is according to the ISO standard.  Options:
  1455. \begin{description}
  1456.     \termitem{syntax_errors}{atom or variable}
  1457. Define the behaviour for when a syntax error occurs.  The possible values
  1458.     \begin{description}
  1459.         \termitem{fail}{}
  1460.     Default behaviour.  The error is reported as a warning and the predicate
  1461.     fails.
  1462.         \termitem{quiet}{}
  1463.     Quietly fails if a syntax error has occurred.
  1464.         \termitem{\arg{Variable}}{}
  1465.     If no error occurs, the variable is unified with \const{none}, otherwise
  1466.     \arg{Variable} is unified with a term of the form
  1467. \begin{code}
  1468. '$stream_position'(CharNo, LineNo, LinePos):Message
  1469. \end{code}
  1470.     This behaviour is a SWI-Prolog extension.
  1471.     \end{description}
  1472.     \termitem{variable_names}{Vars}
  1473. Unify \arg{Vars} with a list of `\arg{Name} = \arg{Var}', where \arg{Name} is an atom describing the variable name and \arg{Var} is a
  1474. variable that shares with the corresponding variable in \arg{Term}.
  1475.     \termitem{singletons}{Vars}
  1476. As \const{variable_names}, but only reports the variables occurring only
  1477. once in the \arg{Term} read. Variables starting with an underscore
  1478. (`\chr{_}') are not included in this list.
  1479.     \termitem{term_position}{Pos}
  1480. Unifies \arg{Pos} with the starting position of the term read.  \arg{Pos}
  1481. if of the same format as use by stream_position/3.
  1482.     \termitem{subterm_positions}{TermPos}
  1483. Describes the detailed layout of the term. The formats for the various
  1484. types of terms if given below. All positions are character positions. If
  1485. the input is related to a normal stream, these positions are relative to
  1486. the start of the input, when reading from the terminal, they are
  1487. relative to the start of the term.
  1488.     \begin{description}
  1489.         \definition{\arg{From}-\arg{To}}
  1490.     Used for primitive types (atoms, numbers, variables).
  1491.         \termitem{string_position}{\arg{From}, \arg{To}}
  1492.     Used to indicate the position of a string enclosed in double
  1493.     quotes (\chr{"}).
  1494.         \termitem{brace_term_position}{\arg{From}, \arg{To}, \arg{Arg}}
  1495.     Term of the form \exam{\{\ldots \}}, as used in DCG rules.  \arg{Arg}
  1496.     describes the argument.
  1497.         \termitem{list_position}{\arg{From}, \arg{To},
  1498.                   \arg{Elms}, \arg{Tail}}
  1499. A list. \arg{Elms} describes the positions of the elements. If the list
  1500. specifies the tail as \mbox{\chr{|}<TailTerm>}, \arg{Tail} is unified
  1501. with the term-position of the tail, otherwise with the atom \const{none}.
  1502.         \termitem{term_position}{\arg{From}, \arg{To},
  1503.                   \arg{FFrom}, \arg{FTo}, \arg{SubPos}}
  1504.     Used for a compound term not matching one of the above.  \arg{FFrom}
  1505.     and \arg{FTo} describe the position of the functor.  \arg{SubPos}
  1506.     is a list, each element of which describes the term-position of the
  1507.     corresponding subterm.
  1508.     \end{description}
  1509. \end{description}
  1510.     \predicate{read_term}{3}{+Stream, -Term, +Options}
  1511. Read term with options from \arg{Stream}.  See read_term/2.
  1512.     \predicate{read_history}{6}{+Show, +Help, +Special, +Prompt, -Term, -Bindings}
  1513. Similar to read_variables/2, but allows for history substitutions.
  1514. read_history/6 is used by the top level to read the user's actions.
  1515. \arg{Show} is the command the user should type to show the saved events.
  1516. \arg{Help} is the command to get an overview of the capabilities.
  1517. \arg{Special} is a list of commands that are not saved in the history.
  1518. \arg{Prompt} is the first prompt given. Continuation prompts for more
  1519. lines are determined by prompt/2. A \const{\%w} in the prompt is
  1520. substituted by the event number. See \secref{history} for available
  1521. substitutions.
  1522. SWI-Prolog calls read_history/6 as follows:
  1523. \begin{code}
  1524. read_history(h, '!h', [trace], '%w ?- ', Goal, Bindings)
  1525. \end{code}
  1526.     \predicate{prompt}{2}{-Old, +New}
  1527. Set prompt associated with read/1 and its derivatives.  \arg{Old}
  1528. is first unified with the current prompt.  On success the prompt will be
  1529. set to \arg{New} if this is an atom.  Otherwise an error message is
  1530. displayed.  A prompt is printed if one of the read predicates is
  1531. called and the cursor is at the left margin.  It is also printed
  1532. whenever a newline is given and the term has not been terminated.
  1533. Prompts are only printed when the current input stream is \arg{user}.
  1534.     \predicate{prompt1}{1}{+Prompt}
  1535. Sets the prompt for the next line to be read.  Continuation lines will
  1536. be read using the prompt defined by prompt/2.
  1537. \end{description}
  1538. \section{Analysing and Constructing Terms}
  1539. \begin{description}
  1540. \predicate{functor}{3}{?Term, ?Functor, ?Arity}
  1541. Succeeds if \arg{Term} is a term with functor \arg{Functor} and arity
  1542. \arg{Arity}.  If \arg{Term} is a variable it is unified with a new term
  1543. holding only variables.  functor/3 silently fails on instantiation
  1544. faults%
  1545.     \footnote{In version 1.2 instantiation faults led to error messages.
  1546.               The new version can be used to do type testing without the
  1547.               need to catch illegal instantiations first.}
  1548. If \arg{Term} is an atom or number, \arg{Functor} will be unified with
  1549. \arg{Term} and arity will be unified with the integer 0 (zero).
  1550. \predicate{arg}{3}{?Arg, ?Term, ?Value}
  1551. \arg{Term} should be instantiated to a term, \arg{Arg} to an integer
  1552. between 1 and the arity of \arg{Term}. \arg{Value} is unified with the
  1553. \arg{Arg}-th argument of \arg{Term}.  \arg{Arg} may also be unbound.
  1554. In this case \arg{Value} will be unified with the successive arguments
  1555. of the term. On successful unification, \arg{Arg} is unified with the
  1556. argument number. Backtracking yields alternative solutions.%
  1557.     \footnote{The instantiation pattern (-, +, ?) is an extension to
  1558.               `standard' Prolog.}
  1559. The predicate arg/3 fails silently if $\arg{Arg} = 0$ or
  1560. $\arg{Arg} > \mbox{\em arity}$ and raises the exception
  1561. \errorterm{domain_error}{not_less_then_zero, \arg{Arg}} if $\arg{Arg} <
  1562. \predicate{setarg}{3}{+Arg, +Term, +Value}
  1563. Extra-logical predicate.  Assigns the \arg{Arg}-th argument of the
  1564. compound term \arg{Term} with the given \arg{Value}.  The assignment
  1565. is undone if backtracking brings the state back into a position before
  1566. the setarg/3 call.
  1567. This predicate may be used for destructive assignment to terms, using
  1568. them as and extra-logical storage bin.
  1569. \infixop{=..}{?Term}{?List}
  1570. \arg{List} is a list which head is the functor of \arg{Term} and the
  1571. remaining arguments are the arguments of the term. Each of the
  1572. arguments may be a variable, but not both.  This predicate is called
  1573. `Univ'.  Examples:
  1574. \begin{code}
  1575. ?- foo(hello, X) =.. List.
  1576. List = [foo, hello, X]
  1577. ?- Term =.. [baz, foo(1)]
  1578. Term = baz(foo(1))
  1579. \end{code}
  1580. \predicate{numbervars}{4}{+Term, +Functor, +Start, -End}
  1581. Unify the free variables of \arg{Term} with a term constructed from the
  1582. atom \arg{Functor} with one argument.  The argument is the number of the
  1583. variable.  Counting starts at \arg{Start}.  \arg{End} is unified with
  1584. the number that should be given to the next variable. Example:
  1585. \begin{code}
  1586. ?- numbervars(foo(A, B, A), this_is_a_variable, 0, End).
  1587. A = this_is_a_variable(0)
  1588. B = this_is_a_variable(1)
  1589. End = 2
  1590. \end{code}
  1591. In Edinburgh Prolog the second argument is missing.  It is fixed to be
  1592. \const{\$VAR}.
  1593. \predicate{free_variables}{2}{+Term, -List}
  1594. Unify \arg{List} with a list of variables, each sharing with a unique variable
  1595. of \arg{Term}. For example:
  1596. \begin{code}
  1597. ?- free_variables(a(X, b(Y, X), Z), L).
  1598. L = [G367, G366, G371]
  1599. X = G367
  1600. Y = G366
  1601. Z = G371
  1602. \end{code}
  1603. \predicate{copy_term}{2}{+In, -Out}
  1604. Make a copy of term \arg{In} and unify the result with \arg{Out}.
  1605. Ground parts of \arg{In} are shared by \arg{Out}.  Provided \arg{In} and
  1606. \arg{Out} have no sharing variables before this call they will have no
  1607. sharing variables afterwards.  copy_term/2 is semantically equivalent
  1608. \begin{code}
  1609. copy_term(In, Out) :-
  1610.         recorda(copy_key, In, Ref),
  1611.         recorded(copy_key, Out, Ref),
  1612.         erase(Ref).
  1613. \end{code}
  1614. \end{description}
  1615. \section{Analysing and Constructing Atoms}
  1616. These predicates convert between Prolog constants and lists of ASCII
  1617. values. The predicates atom_chars/2, number_chars/2 and name/2 behave
  1618. the same when converting from a constant to a list of ASCII values. When
  1619. converting the other way around, atom_chars/2 will generate an atom,
  1620. number_chars will generate a number or fail and name/2 will return a
  1621. number if possible and an atom otherwise.
  1622. \begin{description}
  1623. \predicate{atom_chars}{2}{?Atom, ?String}
  1624. Convert between an atom and a list of ASCII values.  If \arg{Atom} is
  1625. instantiated, if will be translated into a list of ASCII values and the
  1626. result is unified with \arg{String}. If \arg{Atom} is unbound and \arg{String} is a list of ASCII values, it will \arg{Atom} will be unified
  1627. with an atom constructed from this list.
  1628. \predicate{atom_char}{2}{?Atom, ?ASCII}
  1629. Convert between character and ASCII value for a single character.
  1630. \predicate{number_chars}{2}{?Number, ?String}
  1631. Similar to atom_chars/2, but converts between a number and its
  1632. representation as a list of ASCII values.  Fails silently if \arg{Number}
  1633. is unbound and \arg{String} does not describe a number.
  1634. \predicate{name}{2}{?AtomOrInt, ?String}
  1635. \arg{String} is a list of ASCII values describing \arg{Atom}. Each of the
  1636. arguments may be a variable, but not both. When \arg{String} is bound to an
  1637. ASCII value list describing an integer and \arg{Atom} is a variable \arg{Atom}
  1638. will be unified with the integer value described by \arg{String} (e.g.
  1639. `\exam{name(N, "300"), 400 is N + 100}' succeeds).
  1640. \predicate{int_to_atom}{3}{+Int, +Base, -Atom}
  1641. Convert \arg{Int} to an {\sc ascii} representation using base \arg{Base}
  1642. and unify the result with \arg{Atom}. If $\arg{Base} \not= 10$ the base
  1643. will be prepended to \arg{Atom}. $\arg{Base} = 0$ will try to interpret
  1644. \arg{Int} as an ASCII value and return \const{0'}<c>. Otherwise $2 \leq
  1645. \arg{Base} \leq 36$. Some examples are given below.
  1646. \begin{center}\begin{tabular}{lcl}
  1647. int_to_atom(45,  2, A) & $\longrightarrow$ & $A = 2'101101$ \\
  1648. int_to_atom(97,  0, A) & $\longrightarrow$ & $A = 0'a$ \\
  1649. int_to_atom(56, 10, A) & $\longrightarrow$ & $A = 56$ \\
  1650. \end{tabular}\end{center}
  1651. \predicate{int_to_atom}{2}{+Int, -Atom}
  1652. Equivalent to \exam{int_to_atom(Int, 10, Atom)}.
  1653. \predicate{term_to_atom}{2}{?Term, ?Atom}
  1654. Succeeds if \arg{Atom} describes a term that unifies with \arg{Term}. When
  1655. \arg{Atom} is instantiated \arg{Atom} is converted and then unified with
  1656. \arg{Term}. Otherwise \arg{Term} is ``written'' on \arg{Atom} using write/1.
  1657. \predicate{atom_to_term}{3}{+Atom, -Term, -Bindings}
  1658. Use \arg{Atom} as input to read_variables/2 and return the read term in
  1659. \arg{Term} and the variable bindings in \arg{Bindings}.  \arg{Bindings}
  1660. is a list of $\arg{Name} = \arg{Var}$ couples, thus providing access to
  1661. the actual variable names.  See also read_variables/2.
  1662. \predicate{concat}{3}{?Atom1, ?Atom2, ?Atom3}
  1663. \arg{Atom3} forms the concatenation of \arg{Atom1} and \arg{Atom2}.  At
  1664. least two of the arguments must be instantiated to atoms, integers or
  1665. floating point numbers.
  1666. \predicate{concat_atom}{2}{+List, -Atom}
  1667. \arg{List} is a list of atoms, integers or floating point numbers. Succeeds
  1668. if \arg{Atom} can be unified with the concatenated elements of \arg{List}. If
  1669. \arg{List} has exactly 2 elements it is equivalent to concat/3, allowing
  1670. for variables in the list.
  1671. \predicate{concat_atom}{3}{+List, +Separator, -Atom}
  1672. Creates an atom just like concat_atom/2, but inserts \arg{Separator}
  1673. between each pair of atoms.  For example:
  1674. \begin{code}
  1675. ?- concat_atom([gnu, gnat], ', ', A).
  1676. A = 'gnu, gnat'
  1677. \end{code}
  1678. \predicate{atom_length}{2}{+Atom, -Length}
  1679. Succeeds if \arg{Atom} is an atom of \arg{Length} characters long. This
  1680. predicate also works for integers and floats, expressing the number of
  1681. characters output when given to write/1.
  1682. \predicate{atom_prefix}{2}{+Atom, +Prefix}
  1683. Succeeds if \arg{Atom} starts with the characters from \arg{Prefix}.
  1684. Its behaviour is equivalent to \exam{?- concat(\arg{Prefix}, _, \arg{Atom})}, but avoids the construction of an atom for the `remainder'.
  1685. \end{description}
  1686. \section{Representing Text in Strings}        \label{sec:strings}
  1687. SWI-Prolog supports the data type \arg{string}.  Strings are a time
  1688. and space efficient mechanism to handle text in Prolog.  Atoms are
  1689. under some circumstances not suitable because garbage collection on
  1690. them is next to impossible (Although it is possible: BIM_prolog does
  1691. it).  Representing text as a list of ASCII values is, from the logical
  1692. point of view, the cleanest solution.  It however has two drawbacks:
  1693. 1) they cannot be distinguished from a list of (small) integers; and
  1694. 2) they consume (in SWI-Prolog) 12 bytes for each character stored.
  1695. Within strings each character only requires 1 byte storage. Strings
  1696. live on the global stack and their storage is thus reclaimed on
  1697. backtracking.  Garbage collection can easily deal with strings.
  1698. The ISO standard proposes \exam{" \ldots "} is transformed into a string
  1699. object by read/1 and derivatives. This poses problems as in the old
  1700. convention \exam{" \ldots "} is transformed into a list of {\sc ascii}
  1701. characters. For this reason the style check option `\const{string}' is
  1702. available (see style_check/1).
  1703. The set of predicates associated with strings is incomplete and
  1704. tentative.  Names and definitions might change in the future to
  1705. confirm to the emerging standard.
  1706. \begin{description}
  1707. \predicate{string_to_atom}{2}{?String, ?Atom}
  1708. Logical conversion between a string and an atom. At least one of the
  1709. two arguments must be instantiated. \arg{Atom} can also be an integer
  1710. or floating point number.
  1711. \predicate{string_to_list}{2}{?String, ?List}
  1712. Logical conversion between a string and a list of ASCII characters. At
  1713. least one of the two arguments must be instantiated.
  1714. \predicate{string_length}{2}{+String, -Length}
  1715. Unify \arg{Length} with the number of characters in \arg{String}. This
  1716. predicate is functionally equivalent to atom_length/2 and also accepts
  1717. atoms, integers and floats as its first argument.
  1718. \predicate{string_concat}{3}{?String1, ?String2, ?String3}
  1719. Similar to concat/3, but the unbound argument will be unified with a
  1720. string object rather than an atom.  Also, if both \arg{String1} and
  1721. \arg{String2} are unbound and \arg{String3} is bound to text, it
  1722. breaks \arg{String3}, unifying the start with \arg{String1} and the
  1723. end with \arg{String2} as append does with lists.  Note that this
  1724. is not particularly fast on long strings as for each redo the system
  1725. has to create two entirely new strings, while the list equivalent
  1726. only creates a single new list-cell and moves some pointers around.
  1727. \predicate{substring}{4}{+String, +Start, +Length, -Sub}
  1728. Create a substring of \arg{String} that starts at character \arg{Start}
  1729. (1 base) and has \arg{Length} characters. Unify this substring with
  1730. \arg{Sub}.%
  1731.     \footnote{Future versions probably will provide a more logical
  1732.               variant of this predicate.}
  1733. \end{description}
  1734. \section{Operators}
  1735. \begin{description}
  1736. \predicate{op}{3}{+Precedence, +Type, +Name}
  1737. Declare \arg{Name} to be an operator of type \arg{Type} with precedence
  1738. \arg{Precedence}.  \arg{Name} can also be a list of names, in which case
  1739. all elements of the list are declared to be identical operators.  \arg{Precedence} is an integer between 0 and 1200.  Precedence 0 removes
  1740. the declaration.  \arg{Type} is one of: \const{xf}, \const{yf}, 
  1741. \const{xfx}, \const{xfy}, \const{yfx}, \const{yfy}, \const{fy} or \const{fx}.  The
  1742. `\chr{f}' indicates the position of the functor, while \chr{x}
  1743. and \chr{y} indicate the position of the arguments. `\chr{y}'
  1744. should be interpreted as ``on this position a term with precedence lower
  1745. or equal to the precedence of the functor should occur''. For
  1746. `\chr{x}' the precedence of the argument must be strictly lower.
  1747. The precedence of a term is 0, unless its principal functor is an
  1748. operator, in which case the precedence is the precedence of this
  1749. operator. A term enclosed in brackets \exam{(\ldots)} has precedence 0.
  1750. The predefined operators are shown in \tabref{operators}. Note that
  1751. all operators can be redefined by the user.
  1752. \begin{table}
  1753. \begin{center}
  1754. \begin{tabular}{|r|D{f}{f}{-1}|p{4in}|}
  1755. \hline
  1756. 1200 & xfx & \op{-->}, \op{:-} \\
  1757. 1200 & fx & \op{:-}, \op{?-} \\
  1758. 1150 & fx & \op{dynamic}, \op{multifile}, \op{module_transparent},
  1759.             \op{discontiguous}, \op{volatile}, \op{initialization}\\
  1760. 1100 & xfy & \op{;}, \op{|} \\
  1761. 1050 & xfy & \op{->} \\
  1762. 1000 & xfy & \op{,} \\
  1763. 954 & xfy & \op{\} \\
  1764. 900 & fy & \op{\+}, \op{not} \\
  1765. 900 & fx & \op{~} \\
  1766. 700 & xfx & \op{<}, \op{=}, \op{=..}, \op{=@=}, \op{=:=}, \op{=<}, \op{==}, 
  1767.             \op{=\=}, \op{>}, \op{>=}, \op{@<}, \op{@=<}, \op{@>}, 
  1768.             \op{@>=}, \op{\=}, \op{\==}, \op{is} \\
  1769. 600 & xfy & \op{:} \\
  1770. 500 & yfx & \op{+}, \op{-}, \op{/\}, \op{\/}, \op{xor} \\
  1771. 500 & fx & \op{+}, \op{-}, \op{?}, \op{\} \\
  1772. 400 & yfx & \op{*}, \op{/}, \op{//}, \op{<<}, \op{>>}, \op{mod},
  1773.             \op{rem} \\
  1774. 200 & xfx & \op{**} \\
  1775. 200 & xfy & \op{^} \\
  1776. \hline
  1777. \end{tabular}
  1778. \end{center}
  1779.     \caption{System operators}
  1780.     \label{tab:operators}
  1781. \end{table}
  1782. \predicate{current_op}{3}{?Precedence, ?Type, ?Name}
  1783. Succeeds when \arg{Name} is currently defined as an operator of type \arg{Type}
  1784. with precedence \arg{Precedence}. See also op/3.
  1785. \end{description}
  1786. \section{Arithmetic}                \label{sec:arith}
  1787. Arithmetic can be divided into some special purpose integer predicates
  1788. and a series of general predicates for floating point and integer
  1789. arithmetic as appropriate.  The integer predicates are as ``logical'' as
  1790. possible.  Their usage is recommended whenever applicable, resulting in
  1791. faster and more ``logical'' programs.
  1792. The general arithmetic predicates are optionally compiled now (see
  1793. please/3 and the \cmdlineoption{-O} command line option).  Compiled arithmetic
  1794. reduces global stack requirements and improves performance.
  1795. Unfortunately compiled arithmetic cannot be traced, which is why it is
  1796. optional.
  1797. The general arithmetic predicates all handle \arg{expressions}.  An
  1798. expression is either a simple number or a \arg{function}.  The arguments
  1799. of a function are expressions.  The functions are described in
  1800. \secref{functions}.
  1801. \begin{description}
  1802. \predicate{between}{3}{+Low, +High, ?Value}
  1803. \arg{Low} and \arg{High} are integers, $\arg{High} \geq \arg{Low}$. If
  1804. \arg{Value} is an integer, $\arg{Low} \leq \arg{Value} \leq \arg{High}$.
  1805. When \arg{Value} is a variable it is successively bound to all integers
  1806. between \arg{Low} and \arg{High}.
  1807. \predicate{succ}{2}{?Int1, ?Int2}
  1808. Succeeds if $\arg{Int2} = \arg{Int1} + 1$. At least one of the arguments
  1809. must be instantiated to an integer.
  1810. \predicate{plus}{3}{?Int1, ?Int2, ?Int3}
  1811. Succeeds if $\arg{Int3} = \arg{Int1} + \arg{Int2}$. At least two of the
  1812. three arguments must be instantiated to integers.
  1813. \infixop{>}{+Expr1}{+Expr2}
  1814. Succeeds when expression \arg{Expr1} evaluates to a larger number than \arg{Expr2}.
  1815. \infixop{<}{+Expr1}{+Expr2}
  1816. Succeeds when expression \arg{Expr1} evaluates to a smaller number than \arg{Expr2}.
  1817. \infixop{=<}{+Expr1}{+Expr2}
  1818. Succeeds when expression \arg{Expr1} evaluates to a smaller or equal number
  1819. to \arg{Expr2}.
  1820. \infixop{>=}{+Expr1}{+Expr2}
  1821. Succeeds when expression \arg{Expr1} evaluates to a larger or equal number
  1822. to \arg{Expr2}.
  1823. \infixop{=\=}{+Expr1}{+Expr2}
  1824. Succeeds when expression \arg{Expr1} evaluates to a number non-equal to
  1825. \arg{Expr2}.
  1826. \infixop{=:=}{+Expr1}{+Expr2}
  1827. Succeeds when expression \arg{Expr1} evaluates to a number equal to \arg{
  1828. Expr2}.
  1829. \infixop{is}{-Number}{+Expr}
  1830. Succeeds when \arg{Number} has successfully been unified with the number
  1831. \arg{Expr} evaluates to.  If \arg{Expr} evaluates to a float that can be
  1832. represented using an integer (i.e.\ the value is integer and within the
  1833. range that can be described by Prolog's integer representation), \arg{
  1834. Expr} is unified with the integer value. 
  1835. Note that normally, is/2 will be used with unbound left operand.  If
  1836. equality is to be tested, =:=/2 should be used.  For example:
  1837. \begin{center}\begin{tabular}{lp{2.5in}}
  1838. \exam{?- 1.0 is sin({pi}/2).}        & Fails!.  sin({pi}/2) evaluates to 1.0,
  1839.                                      but is/2 will represent this as the
  1840.                                      integer 1, after which unify will
  1841.                                      fail. \\
  1842. \exam{?- 1.0 is float(sin({pi}/2)).} & Succeeds, as the float/1 function
  1843.                                      forces the result to be float. \\
  1844. \exam{?- 1.0 =:= sin({pi}/2).}       & Succeeds as expected.
  1845. \end{tabular}\end{center}
  1846. \end{description}
  1847. \section{Arithmetic Functions}            \label{sec:functions}
  1848. Arithmetic functions are terms which are evaluated by the arithmetic
  1849. predicates described above.  SWI-Prolog tries to hide the difference
  1850. between integer arithmetic and floating point arithmetic from the Prolog
  1851. user.  Arithmetic is done as integer arithmetic as long as possible and
  1852. converted to floating point arithmetic whenever one of the arguments or
  1853. the combination of them requires it.  If a function returns a floating
  1854. point value which is whole it is automatically transformed into an
  1855. integer.  There are three types of arguments to functions:
  1856. \begin{center}\begin{tabular}{lp{4in}}
  1857. \arg{Expr}    & Arbitrary expression, returning either a floating
  1858.           point value or an integer. \\
  1859. \arg{IntExpr}   & Arbitrary expression that should evaluate into
  1860.                   an integer. \\
  1861. \arg{Int}       & An integer.
  1862. \end{tabular}\end{center}
  1863. In case integer addition, subtraction and multiplication would lead to
  1864. an integer overflow the operands are automatically converted to
  1865. floating point numbers.  The floating point functions (sin/1, exp/1,
  1866. etc.)  form a direct interface to the corresponding C library
  1867. functions used to compile SWI-Prolog.  Please refer to the C library
  1868. documentation for details on precision, error handling, etc.
  1869. \begin{description}
  1870. \prefixop{-}{+Expr}
  1871. $\arg{Result} = -\arg{Expr}$
  1872. \infixop{+}{+Expr1}{+Expr2}
  1873. $\arg{Result} = \arg{Expr1} + \arg{Expr2}$
  1874. \infixop{-}{+Expr1}{+Expr2}
  1875. $\arg{Result} = \arg{Expr1} - \arg{Expr2}$
  1876. \infixop{*}{+Expr1}{+Expr2}
  1877. $\arg{Result} = \arg{Expr1} \times \arg{Expr2}$
  1878. \infixop{/}{+Expr1}{+Expr2}
  1879. $\arg{Result} = \frac{\arg{Expr1}}{\arg{Expr2}}$
  1880. \infixop{mod}{+IntExpr1}{+IntExpr2}
  1881. $\arg{Result} = \mod{\arg{Expr1}}{\arg{Expr2}}$ (remainder of division).
  1882. \infixop{rem}{+IntExpr1}{+IntExpr2}
  1883. $\arg{Result} = \rem{\arg{Expr1}}{\arg{Expr2}}$ (remainder of division).
  1884. \infixop{//}{+IntExpr1}{+IntExpr2}
  1885. $\arg{Result} = \arg{Expr1} \div \arg{Expr2}$ (integer division).
  1886. \predicate{abs}{1}{+Expr}
  1887. Evaluate \arg{Expr} and return the absolute value of it.
  1888. \predicate{sign}{1}{+Expr}
  1889. Evaluate to -1 if $\arg{Expr} < 0$, 1 if $\arg{Expr} > 0$ and 0 if
  1890. $\arg{Expr} = 0$.
  1891. \predicate{max}{2}{+Expr1, +Expr2}
  1892. Evaluates to the largest of both \arg{Expr1} and \arg{Expr2}.
  1893. \predicate{min}{2}{+Expr1, +Expr2}
  1894. Evaluates to the smallest of both \arg{Expr1} and \arg{Expr2}.
  1895. \predicate{.}{2}{+Int, []}
  1896. A list of one element evaluates to the element.  This implies \exam{"a"}
  1897. evaluates to the ASCII value of the letter `a' (97). This option is
  1898. available for compatibility only.  It will not work if
  1899. `\exam{style_check(+string)}' is active as \exam{"a"} will then be transformed
  1900. into a string object. The recommended way to specify the ASCII value of
  1901. the letter `a' is \exam{0'a}.
  1902. \predicate{random}{1}{+Int}
  1903. Evaluates to a random integer \arg{i} for which $0 \leq i < \arg{Int}$.
  1904. The seed of this random generator is determined by the system clock when
  1905. SWI-Prolog was started.
  1906. \predicate{round}{1}{+Expr}
  1907. Evaluates \arg{Expr} and rounds the result to the nearest integer.
  1908. \predicate{integer}{1}{+Expr}
  1909. Same as round/1 (backward compatibility).
  1910. \predicate{float}{1}{+Expr}
  1911. Translate the result to a floating point number.  Normally, Prolog will
  1912. use integers whenever possible.  When used around the 2nd argument of 
  1913. is/2, the result will be returned as a floating point number.  In other
  1914. contexts, the operation has no effect.
  1915. \predicate{float_fractional_part}{1}{+Expr}
  1916. Fractional part of a floating-point number.  Negative if \arg{Expr} is
  1917. negative, 0 if \arg{Expr} is integer.
  1918. \predicate{float_integer_part}{1}{+Expr}
  1919. Integer part of floating-point number. Negative if \arg{Expr} is
  1920. negative, \arg{Expr} if \arg{Expr} is integer.
  1921. \predicate{truncate}{1}{+Expr}
  1922. Truncate \arg{Expr} to an integer.  Same as float_integer_part/1.
  1923. \predicate{floor}{1}{+Expr}
  1924. Evaluates \arg{Expr} and returns the largest integer smaller or equal
  1925. to the result of the evaluation.
  1926. \predicate{ceiling}{1}{+Expr}
  1927. Evaluates \arg{Expr} and returns the smallest integer larger or equal
  1928. to the result of the evaluation.
  1929. \predicate{ceil}{1}{+Expr}
  1930. Same as ceiling/1 (backward compatibility).
  1931. \infixop{>>}{+IntExpr}{+IntExpr}
  1932. Bitwise shift \arg{IntExpr1} by \arg{IntExpr2} bits to the right.
  1933. \infixop{<<}{+IntExpr}{+IntExpr}
  1934. Bitwise shift \arg{IntExpr1} by \arg{IntExpr2} bits to the left.
  1935. \infixop{\/}{+IntExpr}{+IntExpr}
  1936. Bitwise `or' \arg{IntExpr1} and \arg{IntExpr2}.
  1937. \infixop{/\}{+IntExpr}{+IntExpr}
  1938. Bitwise `and' \arg{IntExpr1} and \arg{IntExpr2}.
  1939. \infixop{xor}{+IntExpr}{+IntExpr}
  1940. Bitwise `exclusive or' \arg{IntExpr1} and \arg{IntExpr2}.
  1941. \prefixop{\}{+IntExpr}
  1942. Bitwise negation.
  1943. \predicate{sqrt}{1}{+Expr}
  1944. $\arg{Result} = \sqrt{\arg{Expr}}$
  1945. \predicate{sin}{1}{+Expr}
  1946. $\arg{Result} = \sin{\arg{Expr}}$. \arg{Expr} is the angle in radians.
  1947. \predicate{cos}{1}{+Expr}
  1948. $\arg{Result} = \cos{\arg{Expr}}$. \arg{Expr} is the angle in radians.
  1949. \predicate{tan}{1}{+Expr}
  1950. $\arg{Result} = \tan{\arg{Expr}}$. \arg{Expr} is the angle in radians.
  1951. \predicate{asin}{1}{+Expr}
  1952. $\arg{Result} = \arcsin{\arg{Expr}}$. \arg{Result} is the angle in radians.
  1953. \predicate{acos}{1}{+Expr}
  1954. $\arg{Result} = \arccos{\arg{Expr}}$. \arg{Result} is the angle in radians.
  1955. \predicate{atan}{1}{+Expr}
  1956. $\arg{Result} = \arctan{\arg{Expr}}$. \arg{Result} is the angle in radians.
  1957. \predicate{atan}{2}{+YExpr, +XExpr}
  1958. $\arg{Result} = \arctan{\frac{\arg{YExpr}}{\arg{XExpr}}}$. \arg{Result} is the
  1959. angle in radians.  The return value is in the range $[-\pi\ldots\pi]$.
  1960. Used to convert between rectangular and polar coordinate system.
  1961. \predicate{log}{1}{+Expr}
  1962. $\arg{Result} = \ln{\arg{Expr}}$
  1963. \predicate{log10}{1}{+Expr}
  1964. $\arg{Result} = \lg{\arg{Expr}}$
  1965. \predicate{exp}{1}{+Expr}
  1966. $\arg{Result} = \pow{e}{\arg{Expr}}$
  1967. \infixop{**}{+Expr1}{+Expr2}
  1968. $\arg{Result} = \pow{\arg{Expr1}}{\arg{Expr2}}$
  1969. \infixop{^}{+Expr1}{+Expr2}
  1970. Same as **/2.  (backward compatibility).
  1971. \predicate{pi}{0}{}
  1972. Evaluates to the mathematical constant $\pi$ (3.141593).
  1973. \predicate{e}{0}{}
  1974. Evaluates to the mathematical constant $e$ (2.718282).
  1975. \predicate{cputime}{0}{}
  1976. Evaluates to a floating point number expressing the {\sc cpu} time (in seconds)
  1977. used by Prolog up till now. See also statistics/2 and time/1.
  1978. \end{description}
  1979. \section{Adding Arithmetic Functions}
  1980. Prolog predicates can be given the role of arithmetic function.  The
  1981. last argument is used to return the result, the arguments before the
  1982. last are the inputs.  Arithmetic functions are added using the
  1983. predicate arithmetic_function/1, which takes the head as its argument.
  1984. Arithmetic functions are module sensitive, that is they are only
  1985. visible from the module in which the function is defined and declared.
  1986. Global arithmetic functions should be defined and registered from
  1987. module \const{user}.  Global definitions can be overruled locally in
  1988. modules.  The builtin functions described above can be redefined as
  1989. well.
  1990. \begin{description}
  1991. \predicate{arithmetic_function}{1}{+Head}
  1992. Register a Prolog predicate as an arithmetic function (see is/2,
  1993. \predref{>}{2}, etc.). The Prolog predicate should have one more
  1994. argument than specified by \arg{Head}, which it either a term \arg{Name/Arity}, an atom or a complex term. This last argument is an unbound
  1995. variable at call time and should be instantiated to an integer or
  1996. floating point number. The other arguments are the parameters. This
  1997. predicate is module sensitive and will declare the arithmetic function
  1998. only for the context module, unless declared from module \const{user}.
  1999. Example: 
  2000. \begin{code}
  2001. 1 ?- [user].
  2002. :- arithmetic_function(mean/2).
  2003. mean(A, B, C) :-
  2004.         C is (A+B)/2.
  2005. user compiled, 0.07 sec, 440 bytes.
  2006. 2 ?- A is mean(4, 5).
  2007. A = 4.500000
  2008. \end{code}
  2009. \predicate{current_arithmetic_function}{1}{?Head}
  2010. Successively unifies all arithmetic functions that are visible from
  2011. the context module with \arg{Head}.
  2012. \end{description}
  2013. \section{List Manipulation}
  2014. \begin{description}
  2015. \predicate{is_list}{1}{+Term}
  2016. Succeeds if \arg{Term} is bound to the empty list (\exam{[]}) or a term with
  2017. functor `\const{.}' and arity~2.
  2018. \predicate{proper_list}{1}{+Term}
  2019. Equivalent to is_list/1, but also requires the tail of the list to be
  2020. a list (recursively). Examples:
  2021. \begin{code}
  2022. is_list([x|A])          % true
  2023. proper_list([x|A])      % false
  2024. \end{code}
  2025. \predicate{append}{3}{?List1, ?List2, ?List3}
  2026. Succeeds when \arg{List3} unifies with the concatenation of \arg{List1}
  2027. and \arg{List2}. The predicate can be used with any instantiation
  2028. pattern (even three variables).
  2029. \predicate{member}{2}{?Elem, ?List}
  2030. Succeeds when \arg{Elem} can be unified with one of the members of \arg{List}. The predicate can be used with any instantiation
  2031. pattern.
  2032. \predicate{memberchk}{2}{?Elem, +List}
  2033. Equivalent to member/2, but leaves no choice point.
  2034. \predicate{delete}{3}{+List1, ?Elem, ?List2}
  2035. Delete all members of \arg{List1} that simultaneously unify with \arg{Elem} and unify the result with \arg{List2}.
  2036. \predicate{select}{3}{?List1, ?Elem, ?List2}
  2037. Select an element of \arg{List1} that unifies with \arg{Elem}. \arg{List2} is unified with the list remaining from \arg{List1} after
  2038. deleting the selected element. Normally used with the instantiation
  2039. pattern \arg{+List1, -Elem, -List2}, but can also be used to insert an
  2040. element in a list using \arg{-List1, +Elem, +List2}.
  2041. \predicate{nth0}{3}{?Index, ?List, ?Elem}
  2042. Succeeds when the \arg{Index}-th element of \arg{List} unifies with
  2043. \arg{Elem}. Counting starts at 0.
  2044. \predicate{nth1}{3}{?Index, ?List, ?Elem}
  2045. Succeeds when the \arg{Index}-th element of \arg{List} unifies with
  2046. \arg{Elem}. Counting starts at 1.
  2047. \predicate{last}{2}{?Elem, ?List}
  2048. Succeeds if \arg{Elem} unifies with the last element of \arg{List}.
  2049. \predicate{reverse}{2}{+List1, -List2}
  2050. Reverse the order of the elements in \arg{List1} and unify the result
  2051. with the elements of \arg{List2}.
  2052. \predicate{flatten}{2}{+List1, -List2}
  2053. Transform \arg{List1}, possibly holding lists as elements into a `flat'
  2054. list by replacing each list with its elements (recursively). Unify the
  2055. resulting flat list with \arg{List2}. Example:
  2056. \begin{code}
  2057. ?- flatten([a, [b, [c, d], e]], X).
  2058. X = [a, b, c, d, e]
  2059. \end{code}
  2060. \predicate{length}{2}{?List, ?Int}
  2061. Succeeds if \arg{Int} represents the number of elements of list \arg{List}. Can be used to create a list holding only variables.
  2062. \predicate{merge}{3}{+List1, +List2, -List3}
  2063. \arg{List1} and \arg{List2} are lists, sorted to the standard order of
  2064. terms (see \secref{compare}).  \arg{List3} will be unified with an
  2065. ordered list holding both the elements of \arg{List1} and \arg{List2}.
  2066. Duplicates are {\bf not} removed.
  2067. \end{description}
  2068. \section{Set Manipulation}
  2069. \begin{description}
  2070. \predicate{is_set}{1}{+Set}
  2071. Succeeds if \arg{Set} is a proper list (see proper_list/1) without duplicates.
  2072. \predicate{list_to_set}{2}{+List, -Set}
  2073. Unifies \arg{Set} with a list holding the same elements as \arg{List} in
  2074. the same order.  If \arg{list} contains duplicates, only the first is
  2075. retained.  See also sort/2.  Example:
  2076. \begin{code}
  2077. ?- list_to_set([a,b,a], X)
  2078. X = [a,b]
  2079. \end{code}
  2080. \predicate{intersection}{3}{+Set1, +Set2, -Set3}
  2081. Succeeds if \arg{Set3} unifies with the intersection of \arg{Set1} and
  2082. \arg{Set2}. \arg{Set1} and \arg{Set2} are lists without duplicates.
  2083. They need not be ordered.
  2084. \predicate{subtract}{3}{+Set, +Delete, -Result}
  2085. Delete all elements of set `Delete' from `Set' and unify the resulting
  2086. set with `Result'.
  2087. \predicate{union}{3}{+Set1, +Set2, -Set3}
  2088. Succeeds if \arg{Set3} unifies with the union of \arg{Set1} and
  2089. \arg{Set2}. \arg{Set1} and \arg{Set2} are lists without duplicates.
  2090. They need not be ordered.
  2091. \predicate{subset}{2}{+Subset, +Set}
  2092. Succeeds if all elements of \arg{Subset} are elements of \arg{Set} as well.
  2093. \predicate{merge_set}{3}{+Set1, +Set2, -Set3}
  2094. \arg{Set1} and \arg{Set2} are lists without duplicates, sorted to the
  2095. standard order of terms.  \arg{Set3} is unified with an ordered
  2096. list without duplicates holding the union of the elements of \arg{Set1}
  2097. and \arg{Set2}.
  2098. \end{description}
  2099. \section{Sorting Lists}
  2100. \begin{description}
  2101. \predicate{sort}{2}{+List, -Sorted}
  2102. Succeeds if \arg{Sorted} can be unified with a list holding the
  2103. elements of \arg{List}, sorted to the standard order of terms (see
  2104. \secref{compare}).  Duplicates are removed.  Implemented by translating
  2105. the input list into a temporary array, calling the C-library function
  2106. \manref{qsort}{3} using \funcref{PL_compare}{} for comparing the elements,
  2107. after which the result is translated into the result list.
  2108. \predicate{msort}{2}{+List, -Sorted}
  2109. Equivalent to sort/2, but does not remove duplicates.
  2110. \predicate{keysort}{2}{+List, -Sorted}
  2111. \arg{List} is a list of \exam{\arg{Key}-\arg{Value}} pairs (e.g.\ terms
  2112. of the functor `\const{-}' with arity~2). keysort/2 sorts \arg{List}
  2113. like msort/2, but only compares the keys. Can be used to sort terms not
  2114. on standard order, but on any criterion that can be expressed on a
  2115. multi-dimensional scale. Sorting on more than one criterion can be done
  2116. using terms as keys, putting the first criterion as argument 1, the
  2117. second as argument 2, etc. The order of multiple elements that have the
  2118. same \arg{Key} is not changed.
  2119. \predicate{predsort}{3}{+Pred, +List, -Sorted}
  2120. Sorts similar to msort/2, but determines the order of two terms by
  2121. applying \arg{Pred} to pairs of elements from \arg{List} (see apply/2).
  2122. The predicate should succeed if the first element should be before the
  2123. second.
  2124. \end{description}
  2125. \section{Finding all Solutions to a Goal}
  2126. \begin{description}
  2127. \predicate{findall}{3}{+Var, +Goal, -Bag}
  2128. Creates a list of the instantiations \arg{Var} gets successively on
  2129. backtracking over \arg{Goal} and unifies the result with \arg{Bag}.
  2130. Succeeds with an empty list if \arg{Goal} has no solutions. findall/3 is
  2131. equivalent to bagof/3 with all free variables bound with the existence
  2132. operator (\op{^}), except that bagof/3 fails when goal has no
  2133. solutions.
  2134. \predicate{bagof}{3}{+Var, +Goal, -Bag}
  2135. Unify \arg{Bag} with the alternatives of \arg{Var}, if \arg{Goal} has
  2136. free variables besides the one sharing with \arg{Var} bagof will
  2137. backtrack over the alternatives of these free variables, unifying \arg{Bag} with the corresponding alternatives of \arg{Var}. The construct
  2138. \exam{+\arg{Var}{^}\arg{Goal}} tells bagof not to bind \arg{Var} in
  2139. \arg{Goal}. bagof/3 fails if \arg{Goal} has no solutions.
  2140. The example below illustrates bagof/3 and the \op{^} operator. The
  2141. variable bindings are printed together on one line to save paper.
  2142. \begin{code}
  2143. 2 ?- listing(foo).
  2144. foo(a, b, c).
  2145. foo(a, b, d).
  2146. foo(b, c, e).
  2147. foo(b, c, f).
  2148. foo(c, c, g).
  2149. 3 ?- bagof(C, foo(A, B, C), Cs).
  2150. A = a, B = b, C = G308, Cs = [c, d] ;
  2151. A = b, B = c, C = G308, Cs = [e, f] ;
  2152. A = c, B = c, C = G308, Cs = [g] ;
  2153. 4 ?- bagof(C, A^foo(A, B, C), Cs).
  2154. A = G324, B = b, C = G326, Cs = [c, d] ;
  2155. A = G324, B = c, C = G326, Cs = [e, f, g] ;
  2156. \end{code}
  2157. \predicate{setof}{3}{+Var, +Goal, -Set}
  2158. Equivalent to bagof/3, but sorts the result using sort/2 to get a sorted
  2159. list of alternatives without duplicates.
  2160. \end{description}
  2161. \section{Invoking Predicates on all Members of a List}
  2162. All the predicates in this section call a predicate on all members of a
  2163. list or until the predicate called fails.  The predicate is called via
  2164. apply/2, which implies common arguments can be put in front of the
  2165. arguments obtained from the list(s). For example:
  2166. \begin{code}
  2167. ?- maplist(plus(1), [0, 1, 2], X).
  2168. X = [1, 2, 3]
  2169. \end{code}
  2170. we will phrase this as ``\arg{Predicate} is applied on \ldots''
  2171. \begin{description}
  2172. \predicate{checklist}{2}{+Pred, +List}
  2173. \arg{Pred} is applied successively on each element of \arg{List} until
  2174. the end of the list or \arg{Pred} fails. In the latter case the
  2175. checklist/2 fails.
  2176. \predicate{maplist}{3}{+Pred, ?List1, ?List2}
  2177. Apply \arg{Pred} on all successive pairs of elements from \arg{List1}
  2178. and \arg{List2}. Fails if \arg{Pred} can not be applied to a pair. See
  2179. the example above.
  2180. \predicate{sublist}{3}{+Pred, +List1, ?List2}
  2181. Unify \arg{List2} with a list of all elements of \arg{List1} to which
  2182. \arg{Pred} applies.
  2183. \end{description}
  2184. \section{Forall}
  2185. \begin{description}
  2186. \predicate{forall}{2}{+Cond, +Action}
  2187. For all alternative bindings of \arg{Cond} \arg{Action} can be proven.
  2188. The example verifies that all arithmetic statements in the list \arg{L}
  2189. are correct. It does not say which is wrong if one proves wrong.
  2190. \begin{code}
  2191. ?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
  2192.                  Result =:= Formula).
  2193. \end{code}
  2194. \end{description}
  2195. \section{Formatted Write}
  2196. The current version of SWI-Prolog provides two formatted
  2197. write predicates.  The first is writef/[1,2], which is compatible with
  2198. Edinburgh C-Prolog.  The second is format/[1,2], which is compatible
  2199. with Quintus Prolog.  We hope the Prolog community will once define a
  2200. standard formatted write predicate.  If you want performance use
  2201. format/[1,2] as this predicate is defined in C.  Otherwise
  2202. compatibility reasons might tell you which predicate to use.
  2203. \subsection{Writef}
  2204. \begin{description}
  2205. \predicate{write_ln}{1}{+Term}
  2206. Equivalent to \exam{write(Term), nl.}
  2207. \predicate{writef}{1}{+Atom}
  2208. Equivalent to \exam{writef(Atom, []).}
  2209. \predicate{writef}{2}{+Format, +Arguments}
  2210. Formatted write.  \arg{Format} is an atom whose characters will be printed.
  2211. \arg{Format} may contain certain special character sequences which specify
  2212. certain formatting and substitution actions.  \arg{Arguments} then provides
  2213. all the terms required to be output.
  2214.         
  2215. Escape sequences to generate a single special character:
  2216. \begin{center}
  2217. \begin{tabular}{|l|p{3.5in}|}
  2218. \hline
  2219. \fmtseq{\n}   &  Output a nemline character (see also nl/[0,1]) \\
  2220. \fmtseq{\l}   &  Output a line separator (same as \fmtseq{\n}) \\
  2221. \fmtseq{\r}   &  Output a carriage-return character (ASCII 13) \\
  2222. \fmtseq{\t}   &  Output the ASCII character TAB (9) \\
  2223. \fmtseq{\\}   &  The character \chr{\} is output \\
  2224. \fmtseq{\%}   &  The character \chr{%} is output \\
  2225. \fmtseq{\nnn} &  where <nnn> is an integer (1-3 digits) the
  2226.          character with ASCII code <nnn> is output
  2227.          (NB : <nnn> is read as \strong{decimal}) \\
  2228. \hline
  2229. \end{tabular}
  2230. \end{center}
  2231. Note that \fmtseq{\l}, \fmtseq{\<nnn>} and \fmtseq{\\}
  2232. are interpreted differently when character-escapes are in effect. See
  2233. \secref{charescapes}.
  2234. Escape sequences to include arguments from \arg{Arguments}. Each time a
  2235. \% escape sequence is found in \arg{Format} the next argument from \arg{Arguments} is formatted according to the specification.
  2236. \begin{center}
  2237. \begin{tabular}{|l|p{3.5in}|}
  2238. \hline
  2239. \fmtseq{%t}  &  print/1 the next item (mnemonic: term) \\
  2240. \fmtseq{%w}  &  write/1 the next item \\
  2241. \fmtseq{%q}  &  writeq/1 the next item \\
  2242. \fmtseq{%d}  &  display/1 the next item \\
  2243. \fmtseq{%p}  &  print/1 the next item (identical to \fmtseq{%t}) \\
  2244. \fmtseq{%n}  &  Put the next item as a character (i.e. it is
  2245.                 an ASCII value) \\
  2246. \fmtseq{%r}  &  Write the next item N times where N is the
  2247.                 second item (an integer) \\
  2248. \fmtseq{%s}  &  Write the next item as a String (so it must
  2249.                 be a list of characters) \\
  2250. \fmtseq{%f}  &  Perform a ttyflush/0 (no items used) \\
  2251. \fmtseq{%Nc} &  Write the next item Centered in $N$ columns. \\
  2252. \fmtseq{%Nl} &  Write the next item Left justified in $N$ columns. \\
  2253. \fmtseq{%Nr} &  Write the next item Right justified in $N$ columns.
  2254.                 $N$ is a decimal number with at least one digit.
  2255.                 The item must be an atom, integer, float or string. \\
  2256. \hline
  2257. \end{tabular} 
  2258. \end{center}
  2259. \predicate{swritef}{3}{-String, +Format, +Arguments}
  2260. Equivalent to writef/2, but ``writes'' the result on \arg{String} instead
  2261. of the current output stream. Example:
  2262. \begin{code}
  2263. ?- swritef(S, '%15L%w', ['Hello', 'World']).
  2264. S = "Hello          World"
  2265. \end{code}
  2266. \predicate{swritef}{2}{-String, +Format}
  2267. Equivalent to \exam{swritef(String, Format, []).}
  2268. \end{description}
  2269. \subsection{Format}
  2270. \begin{description}
  2271. \predicate{format}{1}{+Format}
  2272. Defined as `\exam{format(Format) :- format(Format, []).}'
  2273. \predicate{format}{2}{+Format, +Arguments}
  2274. \arg{Format} is an atom, list of ASCII values, or a Prolog string.
  2275. \arg{Arguments} provides the arguments required by the format
  2276. specification.  If only one argument is required and this is not a list
  2277. of ASCII values the argument need not be put in a list.  Otherwise the
  2278. arguments are put in a list.
  2279. Special sequences start with the tilde (\chr{~}), followed by an
  2280. optional numeric argument, followed by a character describing the action
  2281. to be undertaken. A numeric argument is either a sequence of digits,
  2282. representing a positive decimal number, a sequence \exam{`<character>},
  2283. representing the ASCII value of the character (only useful for
  2284. \fmtseq{~t}) or a asterisk (\chr{*}), in when the numeric
  2285. argument is taken from the next argument of the argument list, which
  2286. should be a positive integer. Actions are:
  2287. \begin{itemize}
  2288.     \fmtchar{~}
  2289. Output the tilde itself.
  2290.     \fmtchar{a}
  2291. Output the next argument, which should be an atom. This option is
  2292. equivalent to {\bf w}. Compatibility reasons only.
  2293.     \fmtchar{c}
  2294. Output the next argument as an ASCII value. This argument should be an
  2295. integer in the range [0, \ldots, 255] (including 0 and 255).
  2296.     \fmtchar{d}
  2297. Output next argument as a decimal number.  It should be an integer.  If
  2298. a numeric argument is specified a dot is inserted \arg{argument}
  2299. positions from the right (useful for doing fixed point arithmetic with
  2300. integers, such as handling amounts of money).
  2301.     \fmtchar{D}
  2302. Same as {\bf d}, but makes large values easier to read by inserting a
  2303. comma every three digits left to the dot or right.
  2304.     \fmtchar{e}
  2305. Output next argument as a floating point number in exponential
  2306. notation.  The numeric argument specifies the precision.  Default is 6
  2307. digits.  Exact representation depends on the C library function
  2308. printf(). This function is invoked with the format
  2309. \mbox{\tt\%.<precision>e}.
  2310.     \fmtchar{E}
  2311. Equivalent to {\bf e}, but outputs a capital E to indicate the exponent.
  2312.     \fmtchar{f}
  2313. Floating point in non-exponential notation. See C library function
  2314. printf().
  2315.     \fmtchar{g}
  2316. Floating point in {\bf e} or {\bf f} notation, whichever is shorter.
  2317.     \fmtchar{G}
  2318. Floating point in {\bf E} or {\bf f} notation, whichever is shorter.
  2319.     \fmtchar{i}
  2320. Ignore next argument of the argument list. Produces no output.
  2321.     \fmtchar{k}
  2322. Give the next argument to displayq/1 (canonical write).
  2323.     \fmtchar{n}
  2324. Output a newline character.
  2325.     \fmtchar{N}
  2326. Only output a newline if the last character output on this stream was
  2327. not a newline. Not properly implemented yet.
  2328.     \fmtchar{p}
  2329. Give the next argument to print/1.
  2330.     \fmtchar{q}
  2331. Give the next argument to writeq/1.
  2332.     \fmtchar{r}
  2333. Print integer in radix the numeric argument notation. Thus
  2334. \fmtseq{~16r} prints its argument hexadecimal. The argument should
  2335. be in the range $[2, \ldots, 36]$. Lower case letters are used for
  2336. digits above 9.
  2337.     \fmtchar{R}
  2338. Same as {\bf r}, but uses upper case letters for digits above 9.
  2339.     \fmtchar{s}
  2340. Output a string of ASCII characters or a string (see string/1 and
  2341. \secref{strings}) from the next argument.
  2342.     \fmtchar{t}
  2343. All remaining space between 2 tabs tops is distributed equally over
  2344. \fmtseq{~t} statements between the tabs tops. This space is padded
  2345. with spaces by default. If an argument is supplied this is taken to be
  2346. the ASCII value of the character used for padding. This can be used to
  2347. do left or right alignment, centering, distributing, etc. See also
  2348. \fmtseq{~|} and \fmtseq{~+} to set tab stops. A tabs top is
  2349. assumed at the start of each line.
  2350.     \fmtchar{|}
  2351. Set a tabs top on the current position. If an argument is supplied set a
  2352. tabs top on the position of that argument. This will cause all
  2353. \fmtseq{~t}'s to be distributed between the previous and this tabs
  2354.     \fmtchar{+}
  2355. Set a tabs top relative to the current position. Further the same as
  2356. \fmtseq{~|}.
  2357.     \fmtchar{w}
  2358. Give the next argument to write/1.
  2359. \end{itemize}
  2360. Example:
  2361. \begin{code}
  2362. simple_statistics :-
  2363.     <obtain statistics>         % left to the user
  2364.     format('~tStatistics~t~72|~n~n'),
  2365.     format('Runtime: ~`.t ~2f~34|  Inferences: ~`.t ~D~72|~n',
  2366.                                             [RunT, Inf]),
  2367.     ....
  2368. \end{code}
  2369. Will output
  2370. \begin{code}
  2371.                              Statistics
  2372. Runtime: .................. 3.45  Inferences: .......... 60,345
  2373. \end{code}
  2374.     \predicate{format}{3}{+Stream, +Format, +Arguments}
  2375. As format/2, but write the output on the given \arg{Stream}.
  2376. \predicate{sformat}{3}{-String, +Format, +Arguments}
  2377. Equivalent to format/2, but ``writes'' the result on \arg{String}
  2378. instead of the current output stream. Example:
  2379. \begin{code}
  2380. ?- sformat(S, '~w~t~15|~w', ['Hello', 'World']).
  2381. S = "Hello          World"
  2382. \end{code}
  2383. \predicate{sformat}{2}{-String, +Format}
  2384. Equivalent to `\exam{sformat(String, Format, []).}'
  2385. \end{description}
  2386. \subsection{Programming Format}
  2387. \begin{description}
  2388. \predicate{format_predicate}{2}{+Char, +Head}
  2389. If a sequence \fmtseq{~c} (tilde, followed by some character) is
  2390. found, the format derivatives will first check whether the user has
  2391. defined a predicate to handle the format. If not, the built in
  2392. formatting rules described above are used. \arg{Char} is either an {\sc
  2393. ascii} value, or a one character atom, specifying the letter to be
  2394. (re)defined. \arg{Head} is a term, whose name and arity are used to
  2395. determine the predicate to call for the redefined formatting character.
  2396. The first argument to the predicate is the numeric argument of the
  2397. format command, or the atom \const{default} if no argument is specified.
  2398. The remaining arguments are filled from the argument list. The example
  2399. below redefines \fmtseq{~n} to produce \arg{Arg} times return
  2400. followed by linefeed (so a (Grr.) DOS machine is happy with the output).
  2401. \begin{code}
  2402. :- format_predicate(n, dos_newline(_Arg)).
  2403. dos_newline(Arg) :-
  2404.         between(1, Ar, _), put(13), put(10), fail ; true.
  2405. \end{code}
  2406. \end{description}
  2407. \section{Terminal Control}
  2408. The following predicates form a simple access mechanism to the Unix termcap
  2409. library to provide terminal independent I/O for screen terminals.  The
  2410. library package \file{library(tty)} builds on top of these predicates.
  2411. \begin{description}
  2412. \predicate{tty_get_capability}{3}{+Name, +Type, -Result}
  2413. Get the capability named \arg{Name} from the termcap library.  See
  2414. termcap(5) for the capability names. \arg{Type} specifies the type of
  2415. the expected result, and is one of \const{string}, \const{number} or
  2416. \const{bool}.  String results are returned as an atom, number result as
  2417. an integer and bool results as the atom \const{on} or \const{off}.  If
  2418. an option cannot be found this predicate fails silently.  The
  2419. results are only computed once. Successive queries on the same
  2420. capability are fast. 
  2421. \predicate{tty_goto}{2}{+X, +Y}
  2422. Goto position \mbox{(\arg{X}, \arg{Y})} on the screen.  Note that the predicates
  2423. line_count/2 and line_position/2 will not have a well defined
  2424. behaviour while using this predicate.
  2425. \predicate{tty_put}{2}{+Atom, +Lines}
  2426. Put an atom via the termcap library function tputs().  This function
  2427. decodes padding information in the strings returned by tty_get_capability/3
  2428. and should be used to output these strings. \arg{Lines} is the
  2429. number of lines affected by the operation, or 1 if not applicable (as
  2430. in almost all cases).
  2431. \predicate{set_tty}{2}{-OldStream, +NewStream}
  2432. Set the output stream, used by tty_put/2 and tty_goto/2 to a
  2433. specific stream. Default is user_output.
  2434. \end{description}
  2435. \section{Operating System Interaction}
  2436. \begin{description}
  2437. \predicate{shell}{2}{+Command, -Status}
  2438. Execute \arg{Command} on the operating system. \arg{Command} is given to the
  2439. Bourne shell (/bin/sh). \arg{Status} is unified with the exit status of
  2440. the command.
  2441. On \arg{Win32} systems, shell/[1,2] executes the command using the
  2442. CreateProcess() API and waits for the command to terminate. If the
  2443. command ends with a \chr{\&} sign, the command is handed to the
  2444. WinExec() API, which does not wait for the new task to terminate. See
  2445. also win_exec/2.
  2446. \predicate{shell}{1}{+Command}
  2447. Equivalent to `\exam{shell(Command, 0)}'.
  2448. \predicate{shell}{0}{}
  2449. Start an interactive Unix shell.  Default is \file{/bin/sh}, the
  2450. environment variable \env{SHELL} overrides this default.  Not available
  2451. for Win32 platforms.
  2452. \predicate{win_exec}{2}{+Command, +Show}
  2453. Win32 systems only. Spawns a Windows task without waiting for its
  2454. completion.  \arg{Show} is either \const{iconic} or \const{normal} and
  2455. dictates the initial status of the window.  The \const{iconic} option
  2456. is notably handy to start (DDE) servers.
  2457. \predicate{getenv}{2}{+Name, -Value}
  2458. Get Unix environment variable (see csh(1) and sh(1)). Fails if the
  2459. variable does not exist.
  2460. \predicate{setenv}{2}{+Name, +Value}
  2461. Set Unix environment variable.  \arg{Name} and \arg{Value} should be
  2462. instantiated to atoms or integers.  The environment variable will be
  2463. passed to shell/[0-2] and can be requested using getenv/2.
  2464. \predicate{unsetenv}{1}{+Name}
  2465. Remove Unix environment variable from the environment.
  2466. \predicate{get_time}{1}{-Time}
  2467. Return the number of seconds that elapsed since the epoch of Unix,
  2468. 1 January 1970, 0 hours.  \arg{Time} is a floating point number. Its
  2469. granularity is system dependent.  On {\sc sun}, this is 1/60 of a second.
  2470. \predicate{convert_time}{8}{+Time, -Year, -Month, -Day, -Hour, -Minute, -Second, -MilliSeconds}
  2471. Convert a time stamp, provided by get_time/1, time_file/2, etc.  \arg{Year} is unified with the year, \arg{Month} with the month number
  2472. (January is 1), \arg{Day} with the day of the month (starting with 1),
  2473. \arg{Hour} with the hour of the day (0--23), \arg{Minute} with the
  2474. minute (0--59). \arg{Second} with the second (0--59) and \arg{MilliSecond} with the milliseconds (0--999).  Note that the latter
  2475. might not be accurate or might always be 0, depending on the timing
  2476. capabilities of the system.
  2477. \end{description}
  2478. \section{File System Interaction}
  2479. \begin{description}
  2480. \predicate{access_file}{2}{+File, +Mode}
  2481. Succeeds if \arg{File} exists and can be accessed by this prolog
  2482. process under mode \arg{Mode}.  \arg{Mode} is one of the atoms
  2483. \const{read}, \const{write}, \const{append}, \const{exist}, \const{none} or
  2484. \const{execute}. \arg{File} may also be the name of a directory. Fails
  2485. silently otherwise.  \exam{access_file(File, none)} simply succeeds
  2486. without testing anything.
  2487. If `Mode' is \const{write} or \const{append}, this predicate also succeeds
  2488. if the file does not exist and the user has write-access to the
  2489. directory of the specified location.
  2490. \predicate{exists_file}{1}{+File}
  2491. Succeeds when \arg{File} exists. This does not imply the user has read
  2492. and/or write permission for the file.
  2493. \predicate{file_directory_name}{2}{+File, -Directory}
  2494. Extracts the directory-part of \arg{File}. The resulting \arg{Directory}
  2495. name ends with the directory separator character \chr{/}. If \arg{File}
  2496. is an atom that does not contain any directory separator characters, the
  2497. empty atom \const{''} is returned.  See also file_base_name/2.
  2498. \predicate{file_base_name}{2}{+File, -BaseName}
  2499. Extracts the filename part from a path specification. If \arg{File} does
  2500. not contain any directory separators, \arg{File} is returned.
  2501. \predicate{same_file}{2}{+File1, +File2}
  2502. Succeeds if both filenames refer to the same physical file.  That is,
  2503. if \arg{File1} and \arg{File2} are the same string or both names exist
  2504. and point to the same file (due to hard or symbolic links and/or
  2505. relative vs. absolute paths).
  2506. \predicate{exists_directory}{1}{+Directory}
  2507. Succeeds if \arg{Directory} exists. This does not imply the user has read,
  2508. search and or write permission for the directory.
  2509. \predicate{delete_file}{1}{+File}
  2510. Unlink \arg{File} from the Unix file system.
  2511. \predicate{rename_file}{2}{+File1, +File2}
  2512. Rename \arg{File1} into \arg{File2}. Currently files cannot be moved
  2513. across devices.
  2514. \predicate{size_file}{2}{+File, -Size}
  2515. Unify \arg{Size} with the size of \arg{File} in characters.
  2516. \predicate{time_file}{2}{+File, -Time}
  2517. Unify the last modification time of \arg{File} with \arg{Time}. \arg{Time} is a floating point number expressing the seconds elapsed since
  2518. Jan~1, 1970.
  2519. \predicate{absolute_file_name}{2}{+File, -Absolute}
  2520. Expand Unix file specification into an absolute path. User home
  2521. directory expansion (\file{~} and \file{~<user>}) and
  2522. variable expansion is done. The absolute path is canonised: references
  2523. to \file{.} and \file{..} are deleted. SWI-Prolog uses absolute file names to
  2524. register source files independent of the current working directory. See
  2525. also absolute_file_name/3.
  2526. \predicate{absolute_file_name}{3}{+Spec, +Options, -Absolute}
  2527. Converts the given file specification into an absolute path. \arg{Option} is a list of options to guide the conformation process:
  2528. \begin{description}
  2529.     \termitem{extensions}{ListOfExtensions}
  2530. List of file-extensions to try.  Default is \const{''}.  For each
  2531. extension, absolute_file_name/3 will first add the extension and then
  2532. verify the conditions imposed by the other options.  If the condition
  2533. fails, the next extension of the list is tried.  Extensions may be
  2534. specified both as \fileext{.ext} or plain \const{ext}.
  2535.     \termitem{access}{Mode}
  2536. Imposes the condition access_file(\arg{File}, \arg{Mode}).  \arg{Mode}
  2537. is on of \const{read}, \const{write}, \const{append}, \const{exist} or \const{none}.  See also access_file/2.
  2538.     \termitem{file_type}{Type}
  2539. Defines extensions. Current mapping: \const{txt} implies \const{['']},
  2540. \const{prolog} implies \const{['.pl', '']}, \const{executable} implies
  2541. \const{['.so', '']}, \const{qlf} implies \const{['.qlf', '']} and
  2542. \const{directory} implies \const{['']}.
  2543.     \termitem{file_errors}{fail/true}
  2544. Report if the path cannot be resolved or be silent.  The default is
  2545. to stay silent.
  2546.     \termitem{solutions}{first/all}
  2547. If \const{first} (default), the predicates leaves no choice-point.
  2548. Otherwise a choice-point will be left and backtracking may yield
  2549. more solutions.
  2550. \end{description}
  2551.     \predicate{is_absolute_file_name}{1}{+File}
  2552. True if \arg{File} specifies and absolute path-name.  On Unix systems,
  2553. this implies the path starts with a `/'.  For Microsoft based systems
  2554. this implies the path starts with \file{<letter>:}. This predicate is
  2555. intended to provide platform-independent checking for absolute paths.
  2556. See also absolute_file_name/2 and prolog_to_os_filename/2.
  2557.     \predicate{file_name_extension}{3}{?Base, ?Extension, ?Name}
  2558. This predicate is used to add, remove or test filename extensions. The
  2559. main reason for its introduction is to deal with different filename
  2560. properties in a portable manner.  If the file system is case-insensitive,
  2561. testing for an extension will be done case-insensitive too. \arg{Extension} may be specified with or without a leading dot (\chr{.}).
  2562. If an \arg{Extension} is generated, it will not have a leading dot.
  2563. \predicate{expand_file_name}{2}{+WildCard, -List}
  2564. Unify \arg{List} with a sorted list of files or directories matching
  2565. \arg{WildCard}. The normal Unix wildcard constructs `\const{?}',
  2566. `\const{*}', `\const{[\ldots]}' and `\const{\{\ldots\}}' are recognised.
  2567. The interpretation of `\const{\{\ldots\}}' is interpreted slightly
  2568. different from the C shell (csh(1)). The comma separated argument can be
  2569. arbitrary patterns, including `\const{\{\ldots\}}' patterns. The empty
  2570. pattern is legal as well: `\file{\{.pl,\}}' matches either `\file{.pl}'
  2571. or the empty string.
  2572.     \predicate{prolog_to_os_filename}{2}{?PrologPath, ?OsPath}
  2573. Converts between the internal Prolog pathname conventions and the
  2574. operating-system pathname conventions.  The internal conventions are
  2575. Unix and this predicates is equivalent to =/2 (unify) on Unix systems.
  2576. On DOS systems it will change the directory-separator, limit the
  2577. filename length map dots, except for the last one, onto underscores.
  2578.     \predicate{read_link}{3}{+File, -Link, -Target}
  2579. If \arg{File} points to a symbolic link, unify \arg{Link} with the
  2580. value of the link and \arg{Target} to the file the link is pointing to.
  2581. \arg{Target} points to a file, directory or non-existing entry in the
  2582. file system, but never to a link.  Fails if \arg{File} is not a link.
  2583. Fails always on systems that do not support symbolic links.
  2584.     \predicate{tmp_file}{2}{+Base, -TmpName}
  2585. Create a name for a temporary file.  \arg{Base} is an identifier for
  2586. the category of file.  The \arg{TmpName} is guaranteed to be unique.
  2587. If the system halts, it will automatically remove all created temporary
  2588. files.
  2589.     \predicate{chdir}{1}{+Path}
  2590. Change working directory to \arg{Path}.%
  2591.     \bug{Some of the file-I/O predicates use local filenames.  
  2592.          Using chdir/1 while file-bound streams are open causes
  2593.          wrong results on telling/1, seeing/1 and current_stream/3}
  2594. \end{description}
  2595. \section{User Toplevel Manipulation}
  2596. \begin{description}
  2597. \predicate{break}{0}{}
  2598. Recursively start a new Prolog top level. This Prolog top level has its
  2599. own stacks, but shares the heap with all break environments and the top
  2600. level. Debugging is switched off on entering a break and restored on
  2601. leaving one. The break environment is terminated by typing the system's
  2602. \mbox{end-of-file} character (control-D). If the
  2603. \argoption{-t}{toplevel} command line option is given this goal is
  2604. started instead of entering the default interactive top level
  2605. (prolog/0).
  2606. \predicate{abort}{0}{}
  2607. Abort the Prolog execution and start a new top level.  If the
  2608. \argoption{-t}{toplevel} command line options is given this goal is started
  2609. instead of entering the default interactive top level.  Break
  2610. environments are aborted as well.  All open files except for the
  2611. terminal related files are closed.  The input- and output stream again refers
  2612. to \arg{user}.%
  2613. \bug{Erased clauses which could not actually be removed from the
  2614. database, because they are active in the interpreter, will never be
  2615. garbage collected after an abort.}
  2616. \predicate{halt}{0}{}
  2617. Terminate Prolog execution.  Open files are closed and if the command
  2618. line option \cmdlineoption{-tty} is not active the terminal status (see Unix
  2619. stty(1)) is restored.  Hooks may be registered both in Prolog and in
  2620. foreign code.  Prolog hooks are registered using at_halt/1.  halt/0
  2621. is equivalent to \exam{halt(0)}.
  2622. \predicate{halt}{1}{+Status}
  2623. Terminate Prolog execution with given status.  Status is an integer.
  2624. See also halt/0.
  2625. \predicate{prolog}{0}{}
  2626. This goal starts the default interactive top level. Queries are read
  2627. from the stream \const{user_input}. See also the \const{history} feature
  2628. (feature/2). The prolog/0 predicate is terminated (succeeds) by typing
  2629. the end-of-file character (Unix: control-D).
  2630. \end{description}
  2631. The following two hooks allow for expanding queries and handling the
  2632. result of a query.  These hooks are used by the toplevel variable 
  2633. expansion mechanism described in \secref{topvars}.
  2634. \begin{description}
  2635. \predicate{expand_query}{4}{+Query, -Expanded, +Bindings, -ExpandedBindings}
  2636. Hook in module \const{user}, normally not defined.  \arg{Query} and
  2637. \arg{Bindings} represents the query read from the user and the names
  2638. of the free variables as obtained using read_term/3.  If this predicate
  2639. succeeds, it should bind \arg{Expanded} and \arg{ExpandedBindings} to
  2640. the query and bindings to be executed by the toplevel.  This predicate
  2641. is used by the toplevel (prolog/0).  See also expand_answer/2 and
  2642. term_expansion/2.
  2643. \predicate{expand_answer}{2}{+Bindings, -ExpandedBindings} Hook in
  2644. module \const{user}, normally not defined. Expand the result of a
  2645. successfully executed toplevel query. \arg{Bindings} is the query
  2646. $<Name>=<Value>$ binding list from the query. \arg{ExpandedBindings}
  2647. must be unified with the bindings the toplevel should print.
  2648. \end{description}
  2649. \section{Creating a Protocol of the User Interaction}
  2650. SWI-Prolog offers the possibility to log the interaction with the user
  2651. on a file.%
  2652.     \footnote{A similar facility was added to Edinburgh C-Prolog by
  2653.               Wouter Jansweijer.}
  2654. All Prolog interaction, including warnings and tracer output, are written
  2655. on the protocol file.
  2656. \begin{description}
  2657. \predicate{protocol}{1}{+File}
  2658. Start protocolling on file \arg{File}. If there is already a protocol
  2659. file open then close it first. If \arg{File} exists it is truncated.
  2660. \predicate{protocola}{1}{+File}
  2661. Equivalent to protocol/1, but does not truncate the \arg{File} if it
  2662. exists.
  2663. \predicate{noprotocol}{0}{}
  2664. Stop making a protocol of the user interaction.  Pending output is
  2665. flushed on the file.
  2666. \predicate{protocolling}{1}{-File}
  2667. Succeeds if a protocol was started with protocol/1 or protocola/1 and
  2668. unifies \arg{File} with the current protocol output file.
  2669. \end{description}
  2670. \section{Debugging and Tracing Programs}    \label{sec:debugger}
  2671. \begin{description}
  2672. \predicate{trace}{0}{}
  2673. Start the tracer. trace/0 itself cannot be seen in the tracer.  Note that
  2674. the Prolog toplevel treats trace/0 special; it means `trace the next goal'.
  2675. \predicate{tracing}{0}{}
  2676. Succeeds when the tracer is currently switched on.  tracing/0 itself can
  2677. not be seen in the tracer.
  2678. \predicate{notrace}{0}{}
  2679. Stop the tracer. notrace/0 itself cannot be seen in the tracer.
  2680. \predicate{trace}{1}{+Pred}
  2681. Equivalent to \exam{trace(\arg{Pred}, +all)}.
  2682. \predicate{trace}{2}{+Pred, +Ports}
  2683. Put a trace-point on all predicates satisfying the predicate specification
  2684. \arg{Pred}. \arg{Ports} is a list of portnames (\const{call},
  2685. \const{redo}, \const{exit}, \const{fail}). The atom \const{all} refers
  2686. to all ports. If the port is preceded by a \const{-} sign the
  2687. trace-point is cleared for the port. If it is preceded by a \const{+}
  2688. the trace-point is set.
  2689. The predicate trace/2 activates debug mode (see debug/0).  Each time
  2690. a port (of the 4-port model) is passed that has a trace-point set the
  2691. goal is printed as with trace/0.  Unlike trace/0 however, the execution
  2692. is continued without asking for further information.  Examples:
  2693. \begin{center}
  2694. \begin{tabular}{lp{3in}}
  2695. \exam{?- trace(hello).}          & Trace all ports of hello with any arity
  2696.                                    in any module. \\
  2697. \exam{?- trace({foo}/2, +fail).} & Trace failures of {foo}/2 in any module. \\
  2698. \exam{?- trace({bar}/1, -all).}  & Stop tracing {bar}/1.
  2699. \end{tabular}
  2700. \end{center}
  2701. The predicate debugging/0 shows all currently defined trace-points.
  2702. \predicate{notrace}{1}{+Goal}
  2703. Call \arg{Goal}, but suspend the debugger while \arg{Goal} is executing.
  2704. The current implementation cuts the choicepoints of \arg{Goal} after
  2705. successful completion. See once/1.  Later implementations may have the
  2706. same semantics as call/1.
  2707. \predicate{debug}{0}{}
  2708. Start debugger (stop at spy points).
  2709. \predicate{nodebug}{0}{}
  2710. Stop debugger (do not trace, nor stop at spy points).
  2711. \predicate{debugging}{0}{}
  2712. Print debug status and spy points on current output stream.
  2713. \predicate{spy}{1}{+Pred}
  2714. Put a spy point on all predicates meeting the predicate specification
  2715. \arg{Pred}. See \secref{listing}.
  2716. \predicate{nospy}{1}{+Pred}
  2717. Remove spy point from all predicates meeting the predicate specification
  2718. \arg{Pred}.
  2719. \predicate{nospyall}{0}{}
  2720. Remove all spy points from the entire program.
  2721. \predicate{leash}{1}{?Ports}
  2722. Set/query leashing (ports which allow for user interaction). \arg{Ports} is
  2723. one of \arg{+Name}, \arg{-Name}, \arg{?Name} or a list of these.
  2724. \arg{+Name} enables leashing on that port, \arg{-Name} disables it and
  2725. \arg{?Name} succeeds or fails according to the current setting.
  2726. Recognised ports are: \const{call}, \const{redo}, \const{exit}, \const{fail} and
  2727. \const{unify}. The special shorthand \const{all} refers to all ports, 
  2728. \const{full} refers to all ports except for the unify port (default).
  2729. \const{half} refers to the \const{call}, \const{redo} and \const{fail}
  2730. port.
  2731. \predicate{visible}{1}{+Ports}
  2732. Set the ports shown by the debugger. See leash/1 for a description of
  2733. the port specification. Default is \const{full}.
  2734. \predicate{unknown}{2}{-Old, +New}
  2735. Unify \arg{Old} with the current value of the unknown system flag.  On
  2736. success \arg{New} will be used to specify the new value. \arg{New} should be
  2737. instantiated to either \const{fail} or \const{trace} and determines the
  2738. interpreters action when an undefined predicate which is not declared
  2739. dynamic is encountered (see dynamic/1). \const{fail} implies the predicate
  2740. just fails silently. \const{trace} implies the tracer is started. Default is
  2741. \const{trace}.  The unknown flag is local to each module and unknown/2
  2742. is module transparent.  Using it as a directive in a module file will
  2743. only change the unknown flag for that module.  Using the :/2 construct
  2744. the behaviour on trapping an undefined predicate can be changed for
  2745. any module.  Note that if the unknown flag for a module equals \const
  2746. {fail} the system will not call exception/3 and will {\bf not} try
  2747. to resolve the predicate via the dynamic library system.  The system
  2748. will still try to import the predicate from the public module.
  2749. \predicate{style_check}{1}{+Spec}
  2750. Set style checking options.  \arg{Spec} is either \mbox{\tt +<option>}, 
  2751. \mbox{\tt -<option>}, \mbox{\tt ?<option>} or a list of such options.
  2752. \mbox{\tt +<option>} sets a style checking option, \mbox{\tt -<option>} clears
  2753. it and \mbox{\tt ?<option>} succeeds or fails according to the current
  2754. setting. consult/1 and derivatives resets the style checking options to
  2755. their value before loading the file. If---for example---a file containing
  2756. long atoms should be loaded the user can start the file with:
  2757. \begin{code}
  2758. :- style_check(-atom).
  2759. \end{code}
  2760. Currently available options are:
  2761. \begin{center}
  2762. \begin{tabular}{|l|c|p{3.5in}|}
  2763. \hline
  2764. Name & Default & Description \\
  2765. \hline
  2766. \const{singleton}  & on & read_clause/1 (used by consult/1) warns
  2767.                         on variables only appearing once in a term (clause)
  2768.                         which have a name not starting with an underscore. \\
  2769. \const{atom}       & on & read/1 and derivatives will produce an
  2770.                         error message on quoted atoms or strings longer
  2771.                         than 5 lines. \\
  2772. \const{dollar}     & off & Accept dollar as a lower case character, thus
  2773.                         avoiding the need for quoting atoms with dollar signs.
  2774.                         System maintenance use only. \\         
  2775. \const{discontiguous} & on & Warn if the clauses for a predicate are not
  2776.                         together in the same source file. \\
  2777. \const{string}     & off & Read and derivatives transform \const{"\ldots"} into
  2778.                         a prolog string instead of a list of ASCII
  2779.                         characters. \\
  2780. \hline
  2781. \end{tabular}
  2782. \end{center}
  2783. \end{description}
  2784. \section{Obtaining Runtime Statistics}
  2785. \begin{description}
  2786. \predicate{statistics}{2}{+Key, -Value}
  2787. Unify system statistics determined by \arg{Key} with \arg{Value}. The
  2788. possible keys are given in the \tabref{statistics}.
  2789. \begin{table}
  2790. \begin{center}
  2791. \begin{tabular}{|l|p{4in}|}
  2792. \hline
  2793. cputime         & (User) {\sc cpu} time since Prolog was started in seconds \\
  2794. inferences      & Total number of passes via the call and redo ports
  2795.                   since Prolog was started. \\
  2796. heap        & Estimated total size of the heap (see \secref{heap}) \\
  2797. heapused        & Bytes heap in use by Prolog. \\
  2798. heaplimit    & Maximum size of the heap (see \secref{heap}) \\
  2799. local           & Allocated size of the local stack in bytes. \\
  2800. localused       & Number of bytes in use on the local stack. \\
  2801. locallimit      & Size to which the local stack is allowed to grow \\
  2802. global          & Allocated size of the global stack in bytes. \\
  2803. globalused      & Number of bytes in use on the global stack. \\
  2804. globallimit     & Size to which the global stack is allowed to grow \\
  2805. trail           & Allocated size of the trail stack in bytes. \\
  2806. trailused       & Number of bytes in use on the trail stack. \\
  2807. traillimit      & Size to which the trail stack is allowed to grow \\
  2808. atoms           & Total number of defined atoms. \\
  2809. functors        & Total number of defined name/arity pairs. \\
  2810. predicates      & Total number of predicate definitions. \\
  2811. modules         & Total number of module definitions. \\
  2812. codes           & Total amount of byte codes in all clauses. \\
  2813. \hline
  2814. \end{tabular}
  2815. \end{center}
  2816.     \caption{Keys for statistics/2}
  2817.     \label{tab:statistics}
  2818. \end{table}
  2819. \predicate{statistics}{0}{}
  2820. Display a table of system statistics on the current output stream.
  2821. \predicate{time}{1}{+Goal}
  2822. Execute \arg{Goal} just like once/1 (i.e. leaving no choice points),
  2823. but print used time, number of logical inferences and the average
  2824. number of \arg{lips} (logical inferences per second).  Note that
  2825. SWI-Prolog counts the actual executed number of inferences rather than
  2826. the number of passes through the call- and redo ports of the
  2827. theoretical 4-port model.
  2828. \end{description}
  2829. \section{Finding Performance Bottlenecks}
  2830. SWI-Prolog offers a statistical program profiler similar to Unix prof(1)
  2831. for C and some other languages.  A profiler is used as an aid to find
  2832. performance pigs in programs.  It provides information on the time spent
  2833. in the various Prolog predicates.
  2834. The profiler is based on the assumption that if we monitor the functions
  2835. on the execution stack on time intervals not correlated to the program's
  2836. execution the number of times we find a procedure on the environment
  2837. stack is a measure of the time spent in this procedure.  It is
  2838. implemented by calling a procedure each time slice Prolog is active.
  2839. This procedure scans the local stack and either just counts the
  2840. procedure on top of this stack (\const{plain} profiling) or all procedures
  2841. on the stack (\const{cumulative} profiling).  To get accurate results
  2842. each procedure one is interested in should have a reasonable number of
  2843. counts.  Typically a minute runtime will suffice to get a rough overview
  2844. of the most expensive procedures.
  2845. \begin{description}
  2846. \predicate{profile}{3}{+Goal, +Style, +Number}
  2847. Execute \arg{Goal} just like time/1. Collect profiling statistics
  2848. according to style (see profiler/2) and show the top \arg{Number}
  2849. procedures on the current output stream (see show_profile/1). The
  2850. results are kept in the database until reset_profiler/0 or profile/3
  2851. is called and can be displayed again with show_profile/1. profile/3
  2852. is the normal way to invoke the profiler. The predicates below
  2853. are low-level predicates that can be used for special cases.
  2854. \predicate{show_profile}{1}{+Number}
  2855. Show the collected results of the profiler. Stops the profiler first to
  2856. avoid interference from show_profile/1. It shows the top \arg{Number}
  2857. predicates according the percentage {\sc cpu}-time used.%
  2858.     \footnote{show_profile/1 is defined in Prolog and takes a
  2859.               considerable amount of memory.}
  2860. \predicate{profiler}{2}{-Old, +New}
  2861. Query or change the status of the profiler. The status is one of
  2862. \const{off}, \const{plain} or \const{cumulative}. \const{plain} implies the
  2863. time used by children of a predicate is not added to the time of the
  2864. predicate. For status \const{cumulative} the time of children is added
  2865. (except for recursive calls). Cumulative profiling implies the stack
  2866. is scanned up to the top on each time slice to find all active
  2867. predicates.  This implies the overhead grows with the number of active
  2868. frames on the stack.  Cumulative profiling starts debugging mode
  2869. to disable tail recursion optimisation, which would otherwise
  2870. remove the necessary parent environments.  Switching status from
  2871. \const{plain} to \const{cumulative} resets the profiler.  Switching to and
  2872. from status \const{off} does not reset the collected statistics, thus
  2873. allowing to suspend profiling for certain parts of the program.
  2874. \predicate{reset_profiler}{0}{}
  2875. Switches the profiler to \const{off} and clears all collected statistics.
  2876. \predicate{profile_count}{3}{+Head, -Calls, -Promilage}
  2877. Obtain profile statistics of the predicate specified by \arg{Head}.
  2878. \arg{Head} is an atom for predicates with arity 0 or a term with the
  2879. same name and arity as the predicate required (see
  2880. current_predicate/2). \arg{Calls} is unified with the number of `calls'
  2881. and `redos' while the profiler was active. \arg{Promilage} is unified
  2882. with the relative number of counts the predicate was active
  2883. (\const{cumulative}) or on top of the stack (\const{plain}). \arg{Promilage}
  2884. is an integer between 0 and 1000.
  2885. \end{description}
  2886. \section{Memory Management}
  2887. Note: limit_stack/2 and trim_stacks/0 have no effect on machines that do
  2888. not offer dynamic stack expansion.  On these machines these predicates
  2889. simply succeed to improve portability.
  2890. \begin{description}
  2891.     \predicate{garbage_collect}{0}{}
  2892. Invoke the global- and trail stack garbage collector.  Normally the
  2893. garbage collector is invoked automatically if necessary.  Explicit
  2894. invocation might be useful to reduce the need for garbage collections in
  2895. time critical segments of the code.  After the garbage collection
  2896. trim_stacks/0 is invoked to release the collected memory resources.
  2897.     \predicate{limit_stack}{2}{+Key, +Kbytes}
  2898. Limit one of the stack areas to the specified value. \arg{Key} is one of
  2899. \const{local}, \const{global} or \const{trail}. The limit is an integer,
  2900. expressing the desired stack limit in K bytes. If the desired limit is
  2901. smaller than the currently used value, the limit is set to the nearest
  2902. legal value above the currently used value. If the desired value is
  2903. larger than the maximum, the maximum is taken. Finally, if the desired
  2904. value is either 0 or the atom \const{unlimited} the limit is set to its
  2905. maximum. The maximum and initial limit is determined by the command line
  2906. options \cmdlineoption{-L}, \cmdlineoption{-G} and \cmdlineoption{-T}.
  2907.     \predicate{trim_stacks}{0}{}
  2908. Release stack memory resources that are not in use at this moment,
  2909. returning them to the operating system.  Trim stack is a relatively
  2910. cheap call.  It can be used to release memory resources in a
  2911. backtracking loop, where the iterations require typically seconds of
  2912. execution time and very different, potentially large, amounts of
  2913. stack space.  Such a loop should be written as follows:
  2914. \begin{code}
  2915. loop :-
  2916.         generator,
  2917.             trim_stacks,
  2918.             potentially_expensive_operation,
  2919.         stop_condition, !.
  2920. \end{code}
  2921. The prolog top level loop is written this way, reclaiming memory
  2922. resources after every user query.
  2923.     \predicate{stack_parameter}{4}{+Stack, +Key, -Old, +New}
  2924. Query/set a parameter for the runtime stacks.  \arg{Stack} is one
  2925. of \const{local}, \const{global}, \const{trail} or \const{argument}.
  2926. The table below describes the \arg{Key}/\arg{Value} pairs.  Old is first
  2927. unified with the current value.
  2928. \begin{center}
  2929. \begin{tabular}{|l|l|}
  2930. \hline
  2931. \const{limit}       & Maximum size of the stack in bytes \\
  2932. \const{min_free}    & Minimum free space at entry of foreign predicate \\
  2933. \hline
  2934. \end{tabular}
  2935. \end{center}
  2936. This predicate is currently only available on versions that use the
  2937. stack-shifter to enlarge the runtime stacks when necessary.  It's
  2938. definition is subject to change.
  2939. \end{description}
  2940. \section{Windows DDE interface}          \label{sec:DDE}
  2941. The predicates in this section deal with MS-Windows `Dynamic Data
  2942. Exchange' or DDE protocol.%
  2943.         \footnote{This interface is contributed by Don Dwiggins.}
  2944. A Windows DDE conversation is a form of interprocess communication
  2945. based on sending reserved window-events between the communicating
  2946. processes.  
  2947. See also \secref{DLL} for loading Windows DLL's into SWI-Prolog.
  2948. \subsection{DDE client interface}
  2949. The DDE client interface allows Prolog to talk to DDE server programs.
  2950. We will demonstrate the use of the DDE interface using the Windows
  2951. PROGMAN (Program Manager) application:
  2952. \begin{code}
  2953. 1 ?- open_dde_conversation(progman, progman, C).
  2954. C = 0
  2955. 2 ?- dde_request(0, groups, X)
  2956. --> Unifies X with description of groups
  2957. 3 ?- dde_execute(0, '[CreateGroup("DDE Demo")]').
  2958. 4 ?- close_dde_conversation(0).
  2959. \end{code}
  2960. For details on interacting with \program{progman}, use the SDK online
  2961. manual section on the Shell DDE interface. See also the Prolog
  2962. \file{library(progman)}, which may be used to write simple Windows setup
  2963. scripts in Prolog.
  2964. \begin{description}
  2965. \predicate{open_dde_conversation}{3}{+Service, +Topic, -Handle}
  2966. Open a conversation with a server supporting the given service name and
  2967. topic (atoms).  If successful, \arg{Handle} may be used to send
  2968. transactions to the server.  If no willing server is found this
  2969. predicate fails silently.
  2970. \predicate{close_dde_conversation}{1}{+Handle}
  2971. Close the conversation associated with \arg{Handle}.  All opened
  2972. conversations should be closed when they're no longer needed, although
  2973. the system will close any that remain open on process termination.
  2974. \predicate{dde_request}{3}{+Handle, +Item, -Value}
  2975. Request a value from the server.  \arg{Item} is an atom that identifies
  2976. the requested data, and \arg{Value} will be a string (\const{CF_TEXT} data
  2977. in DDE parlance) representing that data, if the request is successful.
  2978. If unsuccessful, \arg{Value} will be unified with a term of form
  2979. \mbox{\tt error(<Reason>)}, identifying the problem.  This call uses
  2980. SWI-Prolog string objects to return the value rather then atoms to
  2981. reduce the load on the atom-space.  See \secref{strings} for
  2982. a discussion on this data type.
  2983. \predicate{dde_execute}{2}{+Handle, +Command}
  2984. Request the DDE server to execute the given command-string.  Succeeds
  2985. if the command could be executed and fails with error message otherwise.
  2986. \predicate{dde_poke}{4}{+Handle, +Item, +Command}
  2987. Issue a \const{POKE} command to the server on the specified \arg{Item}.
  2988. Command is passed as data of type \const{CF_TEXT}.
  2989. \end{description}
  2990. \subsection{DDE server mode}
  2991. The (autoload) \file{library(dde)} defines primitives to realise simple
  2992. DDE server applications in SWI-Prolog.  These features are provided as
  2993. of version 2.0.6 and should be regarded prototypes.  The C-part of
  2994. the DDE server can handle some more primitives, so if you need features
  2995. not provided by this interface, please study \file{library(dde)}.
  2996. \begin{description}
  2997. \predicate{dde_register_service}{2}{+Template, +Goal}
  2998. Register a server to handle DDE request or DDE execute requests from
  2999. other applications. To register a service for a DDE request, \arg{Template} is of the form:
  3000. \begin{quote}
  3001. +Service(+Topic, +Item, +Value)
  3002. \end{quote}
  3003. \arg{Service} is the name of the DDE service provided (like
  3004. \program{progman} in the client example above). \arg{Topic} is either an
  3005. atom, indicating \arg{Goal} only handles requests on this topic or a
  3006. variable that also appears in \arg{Goal}. \arg{Item} and \arg{Value} are
  3007. variables that also appear in \arg{Goal}.
  3008. The example below registers the Prolog feature/2 predicate to be
  3009. accessible from other applications.  The request may be given from
  3010. the same Prolog as well as from another application.
  3011. \begin{code}
  3012. ?- dde_register_service(prolog(feature, F, V),
  3013.                         feature(F, V)).
  3014. ?- open_dde_conversation(prolog, feature, Handle),
  3015.    dde_request(Handle, home, Home),
  3016.    close_dde_conversation(Handle).
  3017. Home = '/usr/local/lib/pl-2.0.6/'
  3018. \end{code}
  3019. Handling DDE \const{execute} requests is very similar.  In this case the
  3020. template is of the form:
  3021. \begin{quote}
  3022. +Service(+Topic, +Item)
  3023. \end{quote}
  3024. Passing a \arg{Value} argument is not needed as execute requests either
  3025. succeed or fail.  If \arg{Goal} fails, a `not processed' is passed back
  3026. to the caller of the DDE request.
  3027. \predicate{dde_unregister_service}{1}{+Service}
  3028. Stop responding to \arg{Service}. If Prolog is halted, it will
  3029. automatically call this on all open services.
  3030. \predicate{dde_current_service}{2}{-Service, -Topic}
  3031. Find currently registered services and the topics served on them.
  3032. \predicate{dde_current_connection}{2}{-Service, -Topic}
  3033. Find currently open conversations.
  3034. \end{description}
  3035. \section{Miscellaneous}
  3036. \begin{description}
  3037. \predicate{dwim_match}{2}{+Atom1, +Atom2}
  3038. Succeeds if \arg{Atom1} matches \arg{Atom2} in `Do What I Mean' sense.
  3039. Both \arg{Atom1} and \arg{Atom2} may also be integers or floats.
  3040. The two atoms match if:
  3041. \begin{shortlist}
  3042.     \item They are identical
  3043.     \item They differ by one character (spy $\equiv$ spu)
  3044.     \item One character is inserted/deleted (debug $\equiv$ deug)
  3045.     \item Two characters are transposed (trace $\equiv$ tarce)
  3046.     \item `Sub-words' are glued differently (existsfile $\equiv$ existsFile $\equiv$ exists_file)
  3047.     \item Two adjacent sub words are transposed (existsFile $\equiv$ fileExists)
  3048. \end{shortlist}
  3049. \predicate{dwim_match}{3}{+Atom1, +Atom2, -Difference}
  3050. Equivalent to dwim_match/2, but unifies \arg{Difference} with an atom
  3051. identifying the the difference between \arg{Atom1} and \arg{Atom2}.  The
  3052. return values are (in the same order as above): \const{equal},
  3053. \const{mismatched_char}, \const{inserted_char}, \const{transposed_char},
  3054. \const{separated} and \const{transposed_word}.
  3055. \predicate{wildcard_match}{2}{+Pattern, +String}
  3056. Succeeds if \arg{String} matches the wildcard pattern \arg{Pattern}. \arg{Pattern} is very similar the the Unix csh pattern matcher.  The patterns
  3057. are given below:
  3058. \begin{center}\begin{tabular}{ll}
  3059. \const{?}         & Matches one arbitrary character. \\
  3060. \const{*}         & Matches any number of arbitrary characters. \\
  3061. \const{[\ldots]}   & Matches one of the characters specified between the
  3062.             brackets. \mbox{\tt <char1>-<char2>} indicates a range. \\
  3063. \const{\{\ldots\}} & Matches any of the patterns of the comma separated
  3064. list between the braces.
  3065. \end{tabular}\end{center}
  3066. Example:
  3067. \begin{code}
  3068. ?- wildcard_match('[a-z]*.{pro,pl}[%~]', 'a_hello.pl%').
  3069. \end{code}
  3070.     \predicate{gensym}{2}{+Base, -Unique}
  3071. Generate a unique atom from base \arg{Base} and unify it with \arg{Unique}.
  3072. \arg{Base} should be an atom. The first call will return \mbox{<base>1}, 
  3073. the next \mbox{<base>2}, etc. Note that this is no warrant that the atom
  3074. is unique in the system.%
  3075. \bug{I plan to supply a real gensym/2 which does give this warrant for
  3076. future versions.}
  3077.     \predicate{sleep}{1}{+Time}
  3078. Suspend execution \arg{Time} seconds. \arg{Time} is either a floating
  3079. point number or an integer. Granularity is dependent on the system's
  3080. timer granularity. A negative time causes the timer to return
  3081. immediately. On most non-realtime operating systems we can only ensure
  3082. execution is suspended for {\bf at least} \arg{Time} seconds.
  3083. \end{description}
  3084.